js獲取元素的滾動高度,和距離頂部的高度
jq:
獲取瀏覽器顯示區域(可視區域)的高度 : $(window).height(); 獲取瀏覽器顯示區域(可視區域)的寬度 : $(window).width(); 獲取頁面的文檔高度 $(document).height(); 獲取頁面的文檔寬度 : $(document).width(); 瀏覽器當前窗口文檔body的高度: $(document.body).height(); 瀏覽器當前窗口文檔body的寬度: $(document.body).width(); 獲取滾動條到頂部的垂直高度 (即網頁被卷上去的高度) $(document).scrollTop(); 獲取滾動條到左邊的垂直寬度 : $(document).scrollLeft(); 獲取或設置元素的寬度: $(obj).width(); 獲取或設置元素的高度: $(obj).height(); 某個元素的上邊界到body最頂部的距離:obj.offset().top;(在元素的包含元素不含滾動條的情況下) 某個元素的左邊界到body最左邊的距離:obj.offset().left;(在元素的包含元素不含滾動條的情況下) 返回當前元素的上邊界到它的包含元素的上邊界的偏移量:obj.offset().top(在元素的包含元素含滾動條的情況下) 返回當前元素的左邊界到它的包含元素的左邊界的偏移量:obj.offset().left(在元素的包含元素含滾動條的情況下)
js:
網頁被卷起來的高度/寬度(即瀏覽器滾動條滾動后隱藏的頁面內容高度)
document.documentElement.scrollTop //firefox document.documentElement.scrollLeft //firefox document.body.scrollTop //IE document.body.scrollLeft //IE
等同於:
$(window).scrollTop()
$(window).scrollLeft()
網頁工作區域的高度和寬度
document.documentElement.clientHeight// IE firefox
等同於:
$(window).height()
元素距離文檔頂端和左邊的偏移值
obj.offsetTop //IE firefox obj.offsetLeft //IE firefox
等同於:
obj.offset().top
obj.offset().left
簡單實例(監控元素在可見視圖中)
效果:當元素出現在可見區域時,改變其css樣式(背景色變紅);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>監控元素出現在視圖中</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<style>
p {
height: 30px;
line-height: 30px;
background: #f3f3f3;
opacity: 0;
}
</style>
</head>
<body>
<div class="main">
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
<p>你好,china!</p>
</div>
</body>
<script>
function Show() {
var Height = $(window).height();
$('p').not('.none').each(function(ind) {
var Top = $(this).offset().top; //元素距離頂部距離
var scroll = $(document).scrollTop(); //滾動高度
console.log(Top + ' ' + scroll);
if(Top - Height - scroll <= 0) {
setTimeout(function() {
$('p').not('.none').eq(ind).addClass('show').css('background', 'red').animate({
opacity: 1
}, 500);
}, 200);
}
});
}
$(function() {
var Height = $(window).height(); //窗口高度
console.log('可視高度:' + Height);
$('.main').find('*').each(function() {
var Top = $(this).offset().top;
if(Top - Height <= 0) {
$(this).addClass('none').css({
'background': '#09f',
'opacity': 1
});
}
});
$(window).scroll(function() {
Show();
})
})
</script>
</html>

