[英]Checking if window.pageYoffset is >= to set value?
當頁面使用pageyoffset滾動經過一定距離時,我正在嘗試更改某些CSS樣式。 我對javascript很陌生,所以不知道如何正確編寫它。
任何幫助將非常感激。
if ((window.pageYOffset) >= 240) { var hero = document.getElementById('hero') hero.style.position = "fixed" hero.style.top = "-140px" }
您的邏輯完全正確,您只需要將對角線包在一個
window.onscroll = function() { }
。
請注意,在以下示例中,我將您的兩個樣式更改替換為僅添加背景的一個樣式更改,以展示此工作。
window.onscroll = function() { if ((window.pageYOffset) >= 240) { var hero = document.getElementById('hero') //hero.style.position = "fixed"; //hero.style.top = "-140px"; hero.style.background = "green"; }; }
#one { height: 500px; }
<div id="one"></div> <div id="hero">Hi</div>
請注意,一旦完成所需的行為,您還應該unbind
滾動功能的unbind
,這可以使用jQuery的.unbind()
方法完成:
$(window).unbind('scroll');
如果您想使用原始JavaScript,則可以選擇使用addEventListener()
和removeEventListener()
。
希望這可以幫助! :)
如果不告訴我,你會明白的
$(window).scroll(function (event) { var scroll = $(window).scrollTop(); console.log(scroll); if (scroll > 800) { $('#hero').css('background-color','yellow'); } else if(scroll<800){ $('#hero').css('background-color','red'); } });
div{ width:50px; height:50px; } #hero{ height:1500px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='hero' style='background-color:red'> </div> <div style='background-color:blue'> </div>
您需要添加一個事件來檢查scoll的位置,例如:
window.addEventListener('scroll', checkScrollPosition);
然后將您的代碼放在函數中以處理事件
function checkScrollPosition(){
if ((window.pageYOffset) >= 240) {
var hero = document.getElementById('hero')
hero.style.position = "fixed"
hero.style.top = "-140px"
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.