為什么會window.scrollTop是未定義的?
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop
Element.scrollTop 屬性獲取或設定元素內容垂直滾動的像素數。
元素的 scrollTop 值是對元素頂部到其最頂部可見內容的距離的度量。當元素的內容不生成垂直滾動條時,其 scrollTop 值為 0。
jQuery(window).on('scroll', function() {
if(window.scrollTop > 0) {
console.log('of the top')
console.log('scroll top value is: ' window.scrollTop)
} else {
console.log('the top')
console.log('scroll top value is: ' window.scrollTop)
}
})
我在控制臺日志中得到的只是:
scroll top value is: undefined
我總是在 if else 中得到評估:
of the top
即使我滾動到頁面頂部。
為什么 window.scrollTop 是未定義的?
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop視窗不算元素嗎?
uj5u.com熱心網友回復:
您需要使用 jQuery $ 識別符號以及 .scrollTop() 的括號 () 才能獲得位置
這是可執行代碼:
<script>
jQuery(window).on('scroll', function() {
if($(window).scrollTop() > 0) {
console.log('of the top')
console.log('scroll top value is: ' $(window).scrollTop())
} else {
console.log('the top')
console.log('scroll top value is: ' $(window).scrollTop())
}
})
</script>
uj5u.com熱心網友回復:
<script> jQuery(window).on('scroll', function() { if($(window).scrollTop() > 0) { console.log('of the top') console.log('scroll top value is: ' $(window).scrollTop()) } else { console.log('the top') console.log('scroll top value is: ' $(window).scrollTop()) } }) </script>
YESSINE 的代碼是正確的。但可以讓它變得簡單
<script>
jQuery(window).on('scroll', function() {
var window = $(window);
if(window.scrollTop() > 0) {
console.log('of the top')
console.log('scroll top value is: ' window.scrollTop())
} else {
console.log('the top')
console.log('scroll top value is: ' window.scrollTop())
}
})
</script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/371614.html
標籤:javascript 查询 滚动
上一篇:物件值中的Jquery陣列
