java offset函数的使用方法_jQuery中offset()方法用法实例

本文实例讲述了jQuery中offset()方法用法。分享给大家供大家参考。具体分析如下:

此方法返回或设置所匹配元素相对于document对象的偏移量。

语法结构一:

$(selector).offset()

获取匹配元素在当前document的相对偏移。

返回的对象包含两个整型属:top和left。

此方法只对可见元素有效。

实例代码:

offset()函数-脚本之家

*{

margin:0px;

padding:0px;

}

.father{

border:1px solid black;

width:400px;

height:300px;

padding:10px;

margin:50px;

}

.children{

height:150px;

width:200px;

margin-left:50px;

background-color:green;

}

$(document).ready(function(){

$("button").click(function(){

a=$(".children").offset();

alert("元素的偏移量坐标是:"+a.top+"|"+a.left+"");

})

})

获取元素的坐标

以上代码可以弹出子div相对于document的偏移量。

语法结构二:

$(selector).offset(value)

设置匹配元素相对于document对象的坐标。

offset()方法可以让我们重新设置元素的位置。这个元素的位置是相对于document对象的。

如果对象原先的position样式属性是static的话,会被改成relative来实现重定位。

参数列表:参数

描述

value

规定以像素计的 top 和 left 坐标。可能的值:

1.值对,比如 {top:200,left:10}。

2.带有top和left 属性的对象。

实例代码:

offset()函数-脚本之家

.father{

border:1px solid black;

width:400px;

height:300px;

}

.children{

height:150px;

width:200px;

background-color:green;

}

$(document).ready(function(){

$("button").click(function(){

$(".children").offset({top:100,left:100})

})

})

点击设置偏移量

以上代码可以设置div相对于document的偏移量。

语法结构三:

使用函数的返回值来设置偏移坐标:

$(selector).offset(function(index,oldoffset))

参数列表:参数

描述

function(index,oldvalue)

规定返回被选元素新偏移坐标的函数:index - 可选。元素的索引。oldvalue - 可选。当前坐标。

实例代码:

offset()函数-脚本之家

.father{

border:1px solid black;

width:400px;

height:300px;

}

.children{

height:150px;

width:200px;

background-color:green;

}

$(document).ready(function(){

$("button").click(function(){

$(".children").offset(function(a,b){

var newpoint= new Object();

newpoint.top=b.top+50;

newpoint.left=b.left+50;

return newpoint;

})

})

})

点击设置偏移量

以上代码同样可以设置元素的偏移,不过值是通过函数返回。

希望本文所述对大家的jQuery程序设计有所帮助。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值