抓取元素位置(position)
1
2
3
4
|
<div class="wrap">
<div class="content"></div>
</div>
<button type="button">按鈕</button>
|
1
2
3
4
5
6
7
8
9
10
11
12
|
.wrap{
width: 150px;
height: 180px;
padding: 30px;
background-color: blue;
.content{
margin-top: 20px;
width: 20px;
height: 20px;
background-color: red;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
//抓取外層容器位置
$("button").click(function(){
let wrapPos = $(".wrap").position();
console.log(wrapPos); //{top:0 ,left:0}
});
//只抓取外層容器的上
$("button").click(function(){
let wrapPos = $(".wrap").position().top;
console.log(wrapPos); //0
});
//抓取內層容器位置
$("button").click(function(){
let contentPos = $(".content").position();
console.log(contentPos); //{top:30 ,left:30}
});
|
內容被外層容器向內推移30px
抓取元素位置(offset)
1
2
3
4
|
<div class="wrap">
<div class="content"></div>
</div>
<button type="button">按鈕</button>
|
1
2
3
4
5
6
7
8
9
10
11
12
|
.wrap{
width: 150px;
height: 180px;
padding: 30px;
background-color: blue;
.content{
margin-top: 20px;
width: 20px;
height: 20px;
background-color: red;
}
}
|
1
2
3
4
5
6
7
8
9
10
11
|
//抓取內層相對距離
$("button").click(function(){
let wrapPos = $(".wrap").offset();
console.log(wrapPos); //{top:0 ,left:0}
});
//抓取內層相對距離
$("button").click(function(){
let contentPos = $(".content").offset();
console.log(contentPos); //{top:50 ,left:30}
});
|
內容被被外容器padding+本身margin的距離
抓取滾動時,視窗對上方距離多少
1
2
3
4
|
$(window).scroll(function() {
let windowTop = $(window).scrollTop();
console.log(windowTop);
});
|
其他相關