最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - window.pageYOffset not working in Chrome - Stack Overflow

programmeradmin2浏览0评论

So I am definitely a beginner at js, and this is probably simple but I don't know why this isn't working. I am trying to get a div to appear when the page Y Offset is greater than 30, but it isn't working.

//js is below

var x = document.getElementById('play');
var ypos = window.pageYOffset;

var see = function() {
    if (ypos > 30) {

    x.style.opacity = 1;

    } else {

        console.log('not working');
    }
}

window.addEventListener("scroll", see);

So I am definitely a beginner at js, and this is probably simple but I don't know why this isn't working. I am trying to get a div to appear when the page Y Offset is greater than 30, but it isn't working.

//js is below

var x = document.getElementById('play');
var ypos = window.pageYOffset;

var see = function() {
    if (ypos > 30) {

    x.style.opacity = 1;

    } else {

        console.log('not working');
    }
}

window.addEventListener("scroll", see);
Share Improve this question asked Jan 26, 2015 at 3:27 BbledsBbleds 31 gold badge1 silver badge2 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 4

Because initial ypos is 0.It isn't updating.It remains zero all the time no matter how much you scroll down.To update it, it should be inside the see() function.So each time you scroll down the window, it will be updated.And it is working.Don't confuse it with "not working" statement.It was simply because,ypos variable was assigned to same "0" value.See my example .I have changed it.It will set the opacity to 0.4 when ypos>30

var x = document.getElementById('play');


var see = function() {
var ypos = window.pageYOffset;
    if (ypos > 30) {

    x.style.opacity = '0.4';

    } else {

        alert('scrolled more than 30 !!');
    }
}

window.addEventListener("scroll", see);
<div style='width:600px;height:2000px;background:red;border:1px solid black;' id='play'>lol</div>

发布评论

评论列表(0)

  1. 暂无评论