今天是9月30号,明天就迎来国庆七天小长假了,哈哈哈~~~~提前祝大家国庆节快乐!
前几天写过一篇文章,jquery toggle()设置从上往下滑动,jquery toggle()方向,在文章的后面,介绍了一些jquery动画效果的使用方法,让大家温故而知新。今天主要讲一下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};
});