jquery.offset()使用方法总结

jquery.offset()应用背景

很多时候需要对某个div进行定位,或者获取某个元素相对于document的位置,那么我们会用到jquery.offset()。

获得元素相对于document的位置

获得位置是元素相对于document的位置信息,通常可以说是这个元素的坐标值。

// 元素相对于document的左位移
$("#haorooms-id").offset().left
// 元素相对于document的上位移
$("#haorooms-id").offset().top

设置元素相对于document的位置

$(".haorooms").click(function(){
  x=$("p").offset();
  $("#span1").text(x.left);
  $("#span2").text(x.top);
});

这个案例是我们在点击haorooms标签的时候,在id=span1和id=span2上面显示p标签的left值和top值。

也可以用数组方式设置haorooms-id的位置,如下

// 设置元素相对于document的位移,该元素的position必须为非static值
$("#haorooms-id").offset({left:123,top:99});

注意:

需要注意的是,offset的设置值,必须成对出现,否则会报错的哦!

offset不仅可以设置单个元素,也可以设置多个元素不同的坐标值,而不需要jQuery.each操作了,如:

$(".haorooms-class").offset(function(index,haorooms)
{
    // index为元素索引
    // haorooms为元素的坐标:top、left
    // 函数必须返回坐标值
    return {top:haorooms.top+index,left:haorooms.left+index};
});

 

posted @ 2015-08-27 18:28  TodayCC  阅读(372)  评论(0)    收藏  举报