手机
当前位置:查字典教程网 >编程开发 >Javascript教程 >浅谈jQuery的offset()方法及示例分享
浅谈jQuery的offset()方法及示例分享
摘要:offset()方法的定义和用法:此方法返回或设置所匹配元素相对于document对象的偏移量。语法结构一:$(selector).offs...

offset()方法的定义和用法:

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

语法结构一:

$(selector).offset()

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

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

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

实例代码:

<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <style type="text/css"> *{ 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; } </style> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ a=$(".children").offset(); alert("元素的偏移量坐标是:"+a.top+"|"+a.left+""); }) }) </script> </head> <body> <div> <div></div> </div> <button>获取元素的坐标</button> </body> </html>

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

语法结构二:

$(selector).offset(value)

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

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

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

参数列表:

参数描述

value规定以像素计的 top 和 left 坐标。

可能的值:

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

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

实例代码:

<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <style type="text/css"> .father{ border:1px solid black; width:400px; height:300px; } .children{ height:150px; width:200px; background-color:green; } </style> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $(".children").offset({top:100,left:100}) }) }) </script> </head> <body> <div> <div></div> </div> <button>点击设置偏移量</button> </body> </html>

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

语法结构三:

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

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

参数列表:

参数描述

function(index,oldvalue)规定返回被选元素新偏移坐标的函数:

index - 可选。元素的索引。

oldvalue - 可选。当前坐标。

实例代码:

<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <style type="text/css"> .father{ border:1px solid black; width:400px; height:300px; } .children{ height:150px; width:200px; background-color:green; } </style> <script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script> <script type="text/javascript"> $(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; }) }) }) </script> </head> <body> <div> <div></div> </div> <button>点击设置偏移量</button> </body> </html>

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

以上所述就是本文的全部内容了,希望大家能够喜欢。

【浅谈jQuery的offset()方法及示例分享】相关文章:

7个有用的jQuery代码片段分享

动态加载jQuery的方法

浅谈JavaScript中的Math.atan()方法的使用

简介JavaScript中的setTime()方法的使用

JavaScript中的sub()方法的使用介绍

JQuery中层次选择器用法实例详解

JQuery实现带排序功能的权限选择实例

JQuery中clone方法复制节点

jQuery实现给页面换肤的方法

jQuery取消ajax请求的方法

精品推荐
分类导航