admin管理员组文章数量:1431776
I'm trying to change some css styling when the page is scrolled past a certain distance using pageyoffset. I'm very new to javascript so don't know how to correctly write it.
Any help would be much appreciated.
if ((window.pageYOffset) >= 240) {
var hero = document.getElementById('hero')
hero.style.position = "fixed"
hero.style.top = "-140px"
}
I'm trying to change some css styling when the page is scrolled past a certain distance using pageyoffset. I'm very new to javascript so don't know how to correctly write it.
Any help would be much appreciated.
if ((window.pageYOffset) >= 240) {
var hero = document.getElementById('hero')
hero.style.position = "fixed"
hero.style.top = "-140px"
}
Share
Improve this question
asked Oct 12, 2017 at 2:48
moderategamermoderategamer
2113 silver badges11 bronze badges
3 Answers
Reset to default 4You have the logic exactly right, you simply need to wrap your conditoinal inside a
window.onscroll = function() { }
.
Note that in the following example, I've replaced your two style changes with one that simply adds a background, to showcase this working.
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>
Note that you should also unbind
the scroll functionality once the desired behaviour has been pleted, which can be done with jQuery's .unbind()
method:
$(window).unbind('scroll');
You could alternatively use addEventListener()
and removeEventListener()
if you want to stick with vanilla JavaScript.
Hope this helps! :)
You will get the idea if don't tell me
$(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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='hero' style='background-color:red'>
</div>
<div style='background-color:blue'>
</div>
You'll need to add an event to check for the scoll position like:
window.addEventListener('scroll', checkScrollPosition);
and then put your code above in a function to handle the event
function checkScrollPosition(){
if ((window.pageYOffset) >= 240) {
var hero = document.getElementById('hero')
hero.style.position = "fixed"
hero.style.top = "-140px"
}
}
本文标签: javascriptChecking if windowpageYoffset is gt to set valueStack Overflow
版权声明:本文标题:javascript - Checking if window.pageYoffset is >= to set value? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745564855a2663698.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论