网站首页 语言 会计 电脑 医学 资格证 职场 文艺体育 范文

jQuery中offset()方法运用示例

栏目: 网页设计 / 发布于: / 人气:2.04W
  jQuery中offset()方法运用示例

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

jQuery中offset()方法运用示例

语法结构一:

复制代码 代码如下:$(selector)et()

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

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

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

实例代码:

复制代码 代码如下:

*{

margin:0px;

padding:0px;

}

er{

border:1px solid black;

width:400px;

height:300px;

padding:10px;

margin:50px;

}

dren{

height:150px;

width:200px;

margin-left:50px;

background-color:green;

}

$(document)y(function(){

$("button")k(function(){

a=$("dren")et();

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

})

})

获取元素的坐标

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

语法结构二:

复制代码 代码如下:$(selector)et(value)

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

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

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

参数列表:

参数 描述 value 规定以像素计的 top 和 left 坐标。

可能的值:

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

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

实例代码:

复制代码 代码如下:

er{

border:1px solid black;

width:400px;

height:300px;

}

dren{

height:150px;

width:200px;

background-color:green;

}

$(document)y(function(){

$("button")k(function(){

$("dren")et({top:100,left:100})

})

})

点击设置偏移量

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

语法结构三:

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

复制代码 代码如下:$(selector)et(function(index,oldoffset))

参数列表:

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

index - 可选。元素的索引。

oldvalue - 可选。当前坐标。

实例代码:

复制代码 代码如下:

er{

border:1px solid black;

width:400px;

height:300px;

}

dren{

height:150px;

width:200px;

background-color:green;

}

$(document)y(function(){

$("button")k(function(){

$("dren")et(function(a,b){

var newpoint= new Object();

=+50;

=+50;

return newpoint;

})

})

})

点击设置偏移量

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