本文主要和大家分享jQuery Position方法使用和兼容性的相关知识,position方法获取匹配元素相对父元素的偏移。感兴趣的朋友一起看看吧,希望能帮助到大家。
1、position方法
jquery api地址:http://jquery.cuishifeng.cn/position.html
position方法获取匹配元素相对父元素的偏移。
2、说明
2.1 与offset()区别
.offset()是获得该元素相对于documet的当前坐标
.position()方法可以取得元素相对于父元素的偏移位置,父元素为该元素最近的而且被定位过的祖先元素。
2.2 值计算
.元素本身所占用的边框,边距和填充的大小不计。
.父元素的边框和边距不计,父元素的填充计算在内。
3、示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" />
<title>jQuery position()示例</title>
<style>
html {
line-height: 1.15;
}
.parent {
position: relative;
width: 200px;
height: 400px;
margin-top: 10px;
border: 1px solid green;
padding-top: 10px;
}
.child-1 {
width: 100px;
height: 100px;
margin: 0 auto;
border: 1px solid #2E8DED;
}
.child-2 {
width: 100px;
height: 100px;
margin: 10px auto 0;
border: 1px solid #2E8DED;
padding: 10px;
}
</style>
</head>
<body>
<p class = "parent" >
<p class = "child-1" >
first child
</p>
<p class = "child-2" id= "no-2" >
second child
</p>
</p>
<script src= ".output/js/jquery-1.12.4.min.js" type= "text/javascript" charset= "utf-8" ></script>
<script type= "text/javascript" >
$(document).ready( function () {
console.log($( '#no-2' ).position().top);
});
</script>
</body>
</html>
|
Salin selepas log masuk
4、注意
对于文字的line-height等属性,浏览器(chrome、IE、Firefox)默认大小不一致,因此不同的浏览器position()在计算尺寸时会存在不一致,因此必须保证所有浏览器一致的line-height等属性。
示例代码为没有设置line-height的例子,position()在不同的浏览器上计算出的值不一样。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | <!DOCTYPE html>
<html>
<head>
<meta charset= "utf-8" />
<title>jQuery position()示例</title>
<style>
html {
}
.parent {
position: relative;
width: 200px;
height: 400px;
margin-top: 10px;
border: 1px solid green;
padding-top: 10px;
}
.child-1 {
width: 100px;
height: 100px;
margin: 0 auto;
border: 1px solid #2E8DED;
}
.child-2 {
width: 100px;
height: 100px;
margin: 10px auto 0;
border: 1px solid #2E8DED;
padding: 10px;
}
</style>
</head>
<body>
<p class = "parent" >
文字文字
<p class = "child-1" >
first child
</p>
<p class = "child-2" id= "no-2" >
second child
</p>
</p>
<script src= ".output/js/jquery-1.12.4.min.js" type= "text/javascript" charset= "utf-8" ></script>
<script type= "text/javascript" >
$(document).ready( function () {
console.log($( '#no-2' ).position().top);
});
</script>
</body>
</html>
|
Salin selepas log masuk
相关推荐:
CSS定位position及应用场景实例分析
css的position怎么使用
CSS position属性实例详解
Atas ialah kandungan terperinci jQuery之Position方法使用方法和兼容性详解. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!