窗口滚动无法正常工作

时间:2014-07-29 16:31:32

标签: javascript html

这是我的代码JS

var elem3 = document.createElement('DIV');
elem3.setAttribute('id', 'eye');
elem3.style.display = "block";
elem3.style.width = "100px";
elem3.style.height = "100px";
elem3.style.zIndex = "301";
elem3.style.position = "absolute";
elem3.style.top = "0px";
elem3.style.left = "0px";
document.body.appendChild(elem3);
var danger, up = 0;
window.onscroll = function(e) {
    up += 10;
    document.getElementById('eye').style.top = up + "px";
}

function check() {
    danger = setInterval(function() {
        if (document.getElementById('eye').style.top >= 2000 + "px") {
            location.href = "http://www.google.com";
            clearInterval(danger);
        }
    })
};
check();

我想创建一个div(眼睛)和滚动我希望这个div下降10px.1 scroll = 10px,10 scroll = 100px。如果眼睛的顶部大于2000px,这将重定向页面。但这不起作用,因为当我开始滚动时,页面会自动重定向,div不会滚动到2000px。

2 个答案:

答案 0 :(得分:2)

if (document.getElementById('eye').style.top>=2000+"px"){

检查错误,检查是字符串比较,而不是数字比较。

您应该使用parseInt来获取位置的数字值。

if (parseInt(document.getElementById('eye').style.top,10)>=2000) { ...

为什么在变量up应该保存值时检查样式?

if (up>=2000){ ...

答案 1 :(得分:0)

请勿使用window.onscroll=function(e){up+=10;document.getElementById('eye').style.top=up+"px";}

1)使用scrollTop并在setInterval中添加延迟。

2)您的“if”不起作用,请使用integer代替string

试试这个:

var elem3=document.createElement('DIV');
elem3.setAttribute('id','eye');
elem3.style.display="block";
elem3.style.width="100px";
elem3.style.height="100px";
elem3.style.zIndex="301";
elem3.style.position="absolute";
elem3.style.top="0px";
elem3.style.left="0px";

document.body.appendChild(elem3);

var danger, up=0;
window.onscroll=function(e){
    up = window.scrollTop() + 10; //or `up = window.scrollTop();`
    document.getElementById('eye').style.top = up +"px";
};

function check(){
    danger = setInterval(function(){
        if (parseInt(String(document.getElementById('eye').style.top).replace(/[a-zA-Z]/g)) >= 2000){
            location.href="http://www.google.com";
            clearInterval(danger);
        }
    }, 100);//Added delay
};

check();