今天呢,仍然是簡單的介紹幾個方法,獲取元素對象的尺寸以及元素的位置。在JavaScript中,我們通過offset/client獲取元素在頁面中的位置和尺寸,同樣在jQuery中,我們也需要知道如何去獲取元素的大小以及元素的偏移量。
jQuery獲取元素的尺寸
獲取元素的寬高 —— 內容區的大小
width() height()
// 對象的寬高
console.log($("div").width()); // 返回爲數字型
console.log($("div").height());
寬高 width + padding
innerWidth() innerHeight()
// 包括padding值
console.log($("div").innerWidth());
console.log($("div").innerHeight());
寬度爲:width + padding + border
outerHeight() outerWidth()
// 包括padding和border的值
console.log($("div").outerHeight());
console.log($("div").outerWidth());
寬度:width + padding + border +margin
// padding+border+margin
console.log($("div").outerHeight(true));
console.log($("div").outerWidth(true));
上面方法的返回值均是數值型,沒有單位
jQuery獲取元素的位置
獲取元素的位置有三種方法 offset() position() srcollLeft()/srcollTop()
offset():元素距離文檔的位置;此方法中有兩個屬性top和left。可以獲取元素的位置同時還可以設置元素的偏移,設置屬性值時,需要在方法中傳遞參數,以對象的形式傳遞。
// 1. 距離文檔的距離 有兩個屬性 top和left
console.log($("div").offset().top);
console.log($("div").offset().left);
// 若要更改值 可以在offset方法裏傳對象參數
// $("div").offset({
// top: 300,
// left: 100
// });
position() :元素距離有的定位的父級元素的距離,如果沒有開啓定位的父級元素,則以文檔爲標準.
注意:這個方法只能獲取元素的位置並不能設置。
<style>
.parent {
position: relative;
top: 300px;
width: 200px;
height: 200px;
background-color: saddlebrown;
}
.son {
position: absolute;
top: 20px;
left: 15px;
width: 100px;
height: 100px;
background-color: slategrey;
}
</style>
<div class="parent">
<div class="son"></div>
</div>
// 2. 獲取距離設有定位父級位置position 如果沒有定位的父級 則以文檔爲準
// position方法只能獲取不能設置
console.log($(".son").position());
srcollLeft()/srcollTop() : 頁面滾動時,頁面(或者元素)被捲去的頭部和左側距離
$(window).scroll() 頁面滾動事件;
$(window).scroll(function () {
var top = $(document).scrollTop(); // 頁面捲去的頭部的距離
// 當頁面捲去的頭部的距離 = 內容區距離頂部的距離 返回頂部按鈕顯示
if (top >= $(".box").offset().top) {
$(".back").fadeIn();
} else {
$(".back").fadeOut();
}
})
返回頂部
模擬一下返回頂部的效果:當鼠標滑到內容區域時返回頂部的按鈕顯示,點擊返回頂部按鈕可以回到頂部。
詳細的在代碼的註釋裏都有哈。
<style>
.box {
width: 80%;
height: 800px;
background-color: skyblue;
margin: 500px auto 0;
}
.back {
display: none;
position: fixed;
right: 50px;
top: 500px;
width: 50px;
height: 50px;
background-color: pink;
}
</style>
<div class="box">內容區</div>
<div class="back">返回頂部</div>
<script>
$(function(){
$(window).scroll(function () {
// console.log(11);
var top = $(document).scrollTop(); // 頁面捲去的頭部的距離
// console.log(top);
// 當頁面捲去的頭部的距離 = 內容區距離頂部的距離 返回頂部按鈕顯示
if (top >= $(".box").offset().top) {
$(".back").fadeIn();
} else {
$(".back").fadeOut();
}
})
$(".back").on("click", function () {
// $(document).scrollTop(0);
// 帶動畫的返回頂部
// 只有元素做動畫 切記 不能是文檔 而是body和html元素做動畫
$("body,html").stop().animate({
scrollTop: 0
})
})
})
</script>
堅持讀書的第四天!!!!!