DIV CSS 佈局教程網

jQuery 學習筆記:控制頁面元素實作大全
編輯:JQuery特效代碼     

本文以大量範例整理 jQuery 控制頁面元素的常用操作,從遍歷、屬性、樣式到事件處理,是一份完整的實作參考。

遍歷與屬性操作

each() 遍歷元素

$(document).ready(function () {
$("#btn").html("each()遍歷元素").click(function (event) {
$("div").each(function (index) {
$(this).html("這是第" + index + "個div");
});
event.preventDefault();
});
});

attr 讀寫屬性

// 獲取屬性值
$("div").each(function () {
alert("title屬性的值是:"+$(this).attr("title"));
});
// 設置屬性值
$("div").each(function () {
$(this).attr("style", "color:Red");
});
// 用函數返回值設置
$("div").each(function (index) {
$(this).attr("id", function () {
return "div-id" + index;
}).html($(this).attr("id"));
});

removeAttr 刪除屬性

$("div").removeAttr("title");

樣式處理

addClass / removeClass / toggleClass

$("div").each(function () {
$(this).html(this.title).addClass("myClass1").mouseover(function () {
$(this).toggleClass("myClass2");
});
});

css 直接讀寫樣式

$("div").each(function () {
$(this).html(this.title).css({ color: "Red", opacity: "0.5" }).mouseover(function () {
$(this).css("opacity", "1.0");
}).mouseout(function () {
$(this).css("opacity", "0.5");
});
});

元素內容與移動

text() 取得純文字內容,html() 取得包含 HTML 的內容。移動與複製元素:

$("p").append($("a:eq(0)")); // append/appendTo,單目標移動,多目標複製
$("p:eq(1)").append($("a:eq(1)"));

添加節點用 before()、insertBefore()、after()、insertAfter(),是將元素直接插入到節點之前或之後。

刪除與克隆元素

// remove() 刪除元素
$("p").remove(":contains(P)");
// empty() 刪除所有子元素(與 remove 不同)
$("p").css({border:"1px solid #FF0000",height:"20px"}).empty();
// clone() 克隆元素,可選擇是否連事件一起克隆
$("#btn-k3").html("clone()克隆自己並克隆事件").click(function () {
$(this).clone(true).insertAfter(this);
});

表單值與事件處理

// val() 處理表單元素的值
$("input[type=button]").click(function () {
var sValue = $(this).val();
$("input[type=text]").val(sValue);
});
// one() 只綁定一次事件
$("div").one("click", function () {
$(this).addClass("myClass1").html("只能點一次");
});
// unbind() 刪除事件
$("div").unbind();
// trigger() 自動觸發事件
$(".myClass3").trigger("click");
// toggle() 實現單擊事件動態交替
$("img").toggle(function (event) {
$(event.target).attr("src", "Img/Img2.jpg");
}, function (event) {
$(event.target).attr("src", "Img/Img1.jpg");
});
// hover() 感應鼠標
$("img").hover(function (event) {
$(event.target).css("opacity", "1.0");
}, function (event) {
$(event.target).css("opacity", "0.5");
});

jQuery 事件物件屬性

/*jQuery事件對象的屬性和方法
altKey 按下Alt鍵則為true
ctrlKey 按下Ctrl則為true
keyCode 對於keyup和keydown事件,返回按鍵的值
pageX,pageY 鼠標指針在客戶端的坐標
relatedTarget 鼠標事件中鼠標指針所進入或離開的元素
screenX,screenY 鼠標指針相對於整個屏幕的坐標值
shiftKey 按下shift鍵則為true
target 引起事件的元素/對象
type 事件的名稱
which 鍵盤事件中為按鍵的Unicode值,鼠標事件中代表按鍵的值
stopPropagation() 阻止事件向上冒泡
preventDefault() 阻止事件的默認行為
*/

以上範例搭配的 CSS 類別:

.myClass1{ color:Blue; background:#e58302;}
.myClass2{ color:Red;}
.myClass3{ border:1px solid #FF0000; height:50px; width:80px; float:left;}
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved