亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

jQuery獲取常用屬性

獲取常用屬性

雖然我們可以通過獲取屬性,特性以及 CSS 樣式來取得元素的幾乎所有信息, 但是注意下面的實驗:

<!doctype html>
<html>
<head>
  <meata charset="utf-8"/>
  <title>get object width</title>
  <script src="jquery-1.11.2.min.js"></script>
  <script>
    $(function() {
      alert("attr(\"width\"):" + $("#testDiv").attr("width")); //undifined
      alert("css(\"width\"):" + $("#testDiv").css("width")); //auto(ie6) 或 1264px(ff)
      alert("width():" + $("#testDiv").width()); //正確的數(shù)值 1264
      alert("style.width:" +  $("#testDiv")[0].style.width); //空值
    })
  </script>
</head>
<body>
  <div id="testDiv">test text</div>
</body>
</html>

我們希望獲取測試圖層的寬度,使用 attr 方法獲取"元素特性"為 undefined, 因為并沒有為 div 添加 width。而使用 css()方法雖然可以獲取到 style 屬性的值, 但是在不同瀏覽器里返回的結(jié)果不同,IE6 下返回 auto,而 FF 下雖然返回了正確的數(shù)值但是后面帶有"px"。所以 jQuery 提供了 width()方法,此方法返回的是正確的不帶 px 的數(shù)值。

針對上面的問題,jQuery 為常用的屬性提供了獲取和設(shè)置的方法,比如 width()用戶獲取元素的寬度,而 width(val)用來設(shè)置元素寬度。

下面這些方法可以用來獲取元素的常用屬性值:

HeightAndWidth.jpg

1. 寬和高相關(guān) Height and Width

關(guān)于在獲取長寬的函數(shù)中,要區(qū)別"inner","outer"和 height/width 這三種函數(shù)的區(qū)別:

division.jpg

outerWidth 可以接受一個 bool 值參數(shù)表示是否計算 margin 值。

相信此圖一目了然各個函數(shù)所索取的范圍。圖片以 width 為例說明的,height 的各個函數(shù)同理。

2. 位置相關(guān) Positioning

另外在一些涉及到彈出對象的腳本中,常常需要動態(tài)獲取彈出坐標(biāo)并且設(shè)置元素的位置。

但是很多的計算位置的方法存在著瀏覽器兼容性問題,jQuery 中為我們提供了位置相關(guān)的各個函數(shù):

Positioning.jpg

繼續(xù)學(xué)習(xí)
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script> </head> <style> body{font-family: "微軟雅黑";width: 980px; margin: 0 auto; text-align: center;} .box{ width: 300px; height: 300px; background: green; border: 1px solid #e6e6e6; line-height: 200px; position: absolute; } button{ border: none; background: green; width: 125px; height: 50px; line-height: 50px; color: #fff; font-size: 16px; margin-top: 50px; font-family: "微軟雅黑"; } </style> <body> <button id="btn1">顯示text</button> <button id="btn2">顯示html</button> <button id="btn3">顯示輸入內(nèi)容</button> <p id="text">這是要顯示<b>粗體</b>的節(jié)奏</p> <br /> <input id="input" value="買房子"> <script> $(document).ready(function(){ $("#btn1").click(function(){ alert("Text: " + $("#text").text()); }); $("#btn2").click(function(){ alert("HTML: " + $("#text").html()); }); $("#btn3").click(function(){ alert("Value: " +$("#input").val()); }); }); </script> </body> </html>
提交重置代碼