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
Add a ment  | 

3 Answers 3

Reset to default 4

You 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