深度理解Jquery 中 offset() 方法

來源:互聯網
上載者:User

標籤:style   http   color   io   os   使用   ar   sp   cti   

多說無益,現在就開始!

一、文法

    1、 返回位移座標

         $(selector).offset();

         top: $(selector).offset().top;

         left: $(selector).offset().left;

    2、設定位移座標:

         $(selector).offset({top:value,left:value});

         參數的含義:{top:value,left:value}     當設定位移時是必需的。規定以像素為單位的 top 和 left 座標。

         可能的值:(1)、名/值對,比如 {top:100,left:100} ,  (2)、一個帶有 top 和 left 的對象(執行個體)

        

    3、使用函數設定位移座標:

        $(selector).offset(function(index,currentoffset));

        可選。規定返回包含 top 和 left 座標的對象的函數。
        index - 返回集合中元素的 index 位置。
        currentoffset - 返回被選元素的當前座標。

         

二、offset 的定義和用法

     offset() 方法設定或返回被選元素 相對於文檔的位移座標

     1、當用於返回位移時:

          該方法返回第一個匹配元素的位移座標,它返回一個帶有2個屬性( 以像素為單位的 top 和 left 位置)的對象

     2、當用於設定位移時:

         該方法設定所有匹配元素的位移座標,

三、執行個體

 <!DOCTYPE html>
<html>
<head>
<script src="http://libs.baidu.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){

      名/值 對
       $("button").click(function(){
             $("p").offset({top:200,left:200});
       });

     對象

$("button").click(function(){
newPos=new Object();
newPos.left="0";
newPos.top="100";
$("p").offset(newPos);
});

      函數

$("p").offset(function(n,c){
newPos=new Object();
newPos.left=c.left+100;
newPos.top=c.top+100;
return newPos;
});


});
</script>
</head>
<body>

<p style="border:1px solid red">This is a paragraph.</p>
<button>Set the offset coordinates of the p element</button>

</body>
</html>

四、注意事項

      offset() 方法 返回的top , left. 跟 margin-top,margin-left 也有關係。

      如果元素有margin-top,margin-left. 它擷取當前的margin. 沒有則是預設取值。

      如果父元素也有margin,broder 的話。它也會受到影響。取值要更大。 因為offset() 取的當前與文檔的位移座標。

深度理解Jquery 中 offset() 方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.