Javascript 窗口滚动无法正常工作

Javascript 窗口滚动无法正常工作,javascript,html,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.

这是我的代码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-eye,使用scroll,我希望这个div下降10px。1 scroll=10px,10 scroll=100px。如果眼睛顶部大于2000px,这将重定向页面。但这不起作用,因为当我开始滚动时,页面会自动重定向,而div不会滚动到2000px

if (document.getElementById('eye').style.top>=2000+"px"){
该检查是错误的,该检查是字符串比较,而不是数字比较

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

if (parseInt(document.getElementById('eye').style.top,10)>=2000) { ...
当变量up应该包含该值时,为什么要检查样式

if (up>=2000){ ...
不要使用window.onscroll=function{up+=10;document.getElementById'eye'.style.top=up+px;}

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

2如果不工作,请使用整数而不是字符串

试试这个:

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();

你比我快+1对tip变量的渴望增加:D,现在我想要一个检查此变量的函数,当达到该值时,执行我想要的操作。是的,我解决了。我替换了parseInt。。。。变量加起来了,我笨吗?非常感谢