向下滚动时运行javascript

时间:2015-04-06 14:20:54

标签: javascript html

我无法让我的javascript工作。它应该在“用户”向下滚动2像素时运行但没有任何反应。当我删除Scroll功能时,一切正常,所以我写错了,或者为什么它不起作用?

HTML

<div id="report"></div>
   <div style="position:relative;">
   <img id="myImage" src="test.svg" style="margin-left:200px; width:100px;" />
</div>

的Javascript

(window).scroll(function() {
    if($(window).scrollTop()  > 2) {
        var animate, left=0, imgObj=null, report = document.getElementById('report'), i=0;
        function init(){
            imgObj = document.getElementById('myImage');
            imgObj.style.position= 'absolute'; 
            imgObj.style.top = '240px';
            imgObj.style.left = '-300px';
            imgObj.style.visibility='hidden';
            moveRight();
        } 
        function moveRight(){
            left = parseInt(imgObj.style.left, 10);
            if (10 >= left) {
                imgObj.style.left = (left + 5) + 'px';
                imgObj.style.visibility='visible';

                animate = setTimeout(function(){moveRight();},20); // call moveRight in 20msec
                //stopanimate = setTimeout(moveRight,20);
            } else {
                stop();
            }
            //f();
        }       
        function stop(){
            clearTimeout(animate);
        }
        // starting
        window.onload = function() {init();};
    }
});

1 个答案:

答案 0 :(得分:1)

这里是小提琴,它有效!

http://jsfiddle.net/df6g497p/6/

// you forgot the $ <--- this is all i changed 
$(window).scroll(function() {