基礎知識
- 屏幕可視窗口寬高
**js原生**
document.documentElement.clientWidth // 不包含滾動條寬度
document.documentElement.clientHeight
window.innerWidth // 寬度包含滾動條寬度
window.innerHeight
var win_h = window.innerHeight || document.documentElement.clientHeight //兼容寫法
**jQuery**
$(window).width()
$(window).height()
屏幕可視窗口寬高
- 整個網頁寬高
**js原生**
document.documentElement.scrollWidth
document.documentElement.scrollHeight
**jQuery**
$(document).width()
$(document).height()
整個網頁寬高
- 整個個網頁的上方或者左邊被卷起來的部分
**js原生**
document.documentElement.scrollTop
document.documentElement.scrollLeft
**jQuery**
$(document).scrollTop()
$(document).scrollLeft()
整個個網頁的上方或者左邊被卷起來的部分
- 元素的尺寸和位置
**js原生**
elem.offsetWidth //包含了左右padding+border;
elem.offsetHeight //包含了上下padding+border;
// 下面的兩個和box-sizing 屬性有關,當設為border-box時,返回的寬高包含padding和border,默認時,則不包含。
window.getComputedStyle(elem).width // 返回字符串包含單位px
window.getComputedStyle(elem).height // 返回字符串包含單位px
elem.offsetTop // 相對于第一個已定位的父元素的頂部偏移距離
elem.offsetLeft // 相對于第一個已定位的父元素的左邊偏移距離
**jQuery**
$node.offset().top // 距離文檔頂部的距離
$node.offset().left // 距離文檔左邊的距離
獲取當前頁面滾動條縱坐標的位置
var heightTop = document.documentElement.scrollTop || document.body.scrollTop || window.pageYoffset;
獲取當前頁面滾動條縱坐標的位置
**jQuery**
$node.offset().top;
**js原生**
function getPoint(obj) { //獲取某元素以瀏覽器左上角為原點的坐標
var t = obj.offsetTop; //獲取該元素對應父容器的上邊距
var l = obj.offsetLeft; //對應父容器的上邊距
//判斷是否有父容器,如果存在則累加其邊距
while (obj = obj.offsetParent) {
t += obj.offsetTop; //疊加父容器的上邊距
l += obj.offsetLeft; //疊加父容器的左邊距
}
return {
x:l,
y:t
}
}
var top2 = getPoint(document.getElementsByClassName('btn')[0]);
console.log(top2.y); //2080
監聽某個元素是否已經在可視區域
實現思路:獲取當前監聽元素距離文檔的左上角的top距離;根據這個距離和當前可視區域的高度+文檔滾動距離進行比較,即scrollTop <= top <= document.documentElement.clientHeight + scrollTop
**jQuery**
$(function(){
var top = $("#btn").offset().top; //距離文檔頂部的距離
var windowHeight = document.documentElement.clientHeight; //可視區域的高度
$(window).scroll(function(){
var scrollTop = $(window).scrollTop();
if(top >= scrollTop && top <= windowHeight + scrollTop){
console.log('在可視區域了');
}
});
})
**js原生**
function getPoint(obj) { //獲取某元素以瀏覽器左上角為原點的坐標
var t = obj.offsetTop; //獲取該元素對應父容器的上邊距
var l = obj.offsetLeft; //對應父容器的上邊距
//判斷是否有父容器,如果存在則累加其邊距
while (obj = obj.offsetParent) {
t += obj.offsetTop; //疊加父容器的上邊距
l += obj.offsetLeft; //疊加父容器的左邊距
}
return {
x:l,
y:t
}
}
window.onload = function(){
var top = getPoint(document.getElementById('btn')).y; //距離文檔頂部的距離
var windowHeight = document.documentElement.clientHeight; //可視區域的高度
window.onscroll = function(){
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if(top >= scrollTop && top <= windowHeight + scrollTop){
console.log('在可視區域了');
}
}
}