jQuery 四 基礎DOM和CSS操作

2021-08-17 08:27:23 字數 3609 閱讀 7233

要點:一、設定元素及內容

1.設定和獲取元素中的html內容

id="test">

span>

2.設定和獲取元素中的文字內容

console.log($(

"#test").text()); // this is h1

$("#test").text("我要覆蓋你");

console.log($(

"#test").text()); // 我要覆蓋你

3.設定和獲取表單的內容

console.log($(

"input").val()); // 按鈕

$("input").val("我是按鈕");

console.log($(

"input").val()); // 我是按鈕

如果想設定多個選項的選定狀態,比如下拉列表、單選核取方塊等等,可以通過陣列傳遞操作。

"multiple">

op1option>

op2option>

op3option>

op4option>

$("select").val(["op1", "op4"]); // 值為op1和op4的被選中

二、元素屬性操作

href="###">體育a>
1.獲取屬性

console.log($(

"a").attr("href")); // 獲取href的值, ###

2.設定屬性

$("a").attr("href", "");       // 設定屬性值

console.log($("a").attr("href")); //

屬性值可以為匿名函式

// index表示上次的索引,預設為0

// value表示上次的屬性值

$("a").attr("href", function

(index, value) )

console.log($("a").attr("href")); // 新版本:01

3.刪除屬性

$(

"a").removeattr("href");

console.log($(

"a").attr("href")); // undefined

三、元素樣式操作

id="box">boxdiv>

#box

var box = $("#box");

1.獲採樣式

console.log(box.css("width"));  // 100px
如果獲取的樣式需要計算,那麼可以傳人乙個匿名函式

box.css("width", function

(index, value) );

2.設定樣式

box.css("background", "blue");
3.獲取多個樣式

var style = box.css(["width", "height", "background"]);

for (var v in style)

4.設定多個樣式,可以傳人乙個物件引數

box.css();
5.遍歷元素

$.each(style, function (attr, value) );
6.新增類樣式

#box

.blue

.green

新增blue類

$(

"#box").addclass("blue");

刪除blue類

$(

"#box").removeclass("blue");

切換樣式

$("#box").click(function

() );

我們可以改變切換的頻率

var count = 0;

$("#box").click(function

() );

實現樣式之間的切換

$("#box").click(function

() else

});});

四、css方法

獲取寬度

console.log($(

"#box").width()); // 100

設定寬度

$("#box").width(500);

$("#box").width("500pt"); // 加上單位,預設px

$("#box").width(function

(index, value) );

height() 獲取元素的高度

innerwidth() 獲取元素寬度,包含內邊距 padding

innerheight() 獲取元素高度,包含內邊距 padding

outerwidth() 獲取元素寬度,包含邊框 border 和內邊距 padding

outerheight() 獲取元素高度,包含邊框 border 和內邊距 padding

outerwidth(ture) 同上,且包含外邊距

outerheight(true) 同上,且包含外邊距

以上的使用方法和width()同理,這裡不再累贅

offset() 獲取某個元素相對於視口的偏移位置

* 

#box

// 獲取元素相對於視口的位置

console.log($("#box").offset().left); // 200

console.log($("#box").offset().top); // 200

// position() 獲取某個元素相對于父元素的偏移位置

console.log($("#box").position().left); // 200,父元素就是body

console.log($("#box").position().top); // 200

scrolltop() 獲取垂直滾動條的值

scrolltop(value) 設定垂直滾動條的值

console.log($(window).scrolltop()); // 0

$(document).click(function () );

jQuery基礎之DOM和jQuery之間的轉換

引言 jquery物件 通過jquery包裝dom物件後產生的物件。dom物件不可使用jquery物件的方法。同理jquery物件也不可使用dom物件的方法。例如 foo html 這是jquery物件的使用 它的功能等同於 document.getelementbyid foo innerhtml...

jQuery 基礎DOM和CSS操作

一 設定元素及內容 html 獲取元素中的html內容 html value 設定元素中的html內容 text 獲取元素中的文字內容 text value 設定元素中的文字內容 val 獲取表單中的文字內容 val value 設定表單中的文字內容 注意 當使用html 和text 設定元素的內容...

jquery基礎1 jquery和dom物件轉換

window.nl ad function document ready function 相當於 function foo html 相當於 document.getelementbyid foo innerhtml jquery 物件轉換成 dom物件 第一種方法 var cr cr jquer...