首页 > Web开发 > 详细

深度理解Jquery 中 offset() 方法

时间:2014-09-12 11:49:53      阅读:283      评论:0      收藏:0      [点我收藏+]

多说无益,现在就开始!

一、语法

    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() 方法

原文:http://www.cnblogs.com/htwdz-qhm/p/3967974.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!