在window.location =" #target"之后触发window.addEventListener(' scroll',func)

时间:2015-05-02 09:37:21

标签: javascript javascript-events

我在页面上有一个按钮。当我单击按钮时,页面向下滚动到指定的目标,然后为window事件添加事件侦听器scroll,但滚动事件会立即触发,而不是在用户下次滚动时触发。

有人可以告诉我为什么会这样,以及如何在滚动到指定目标后向window添加滚动事件?我使用的是Firefox 37.0.2

HTML

<button>Click Me!</button>
<!-- Enough br tags to make the page have a scroll bar -->
<div id="target">Text</div>

JS

document.getElementsByTagName('button')[0].addEventListener('click', function(){
    // Both of the following will trigger the scroll event:

    //window.location = '#target';
    //document.getElementById('target').scrollIntoView();

    window.addEventListener('scroll', function(){
        // Removes this function from the window's onscroll event so that it only triggers once
        this.removeEventListener('scroll', arguments.callee);
        alert('Triggered!');
    });
});

1 个答案:

答案 0 :(得分:0)

阅读完评论后,似乎问题是浏览器没有立即滚动。我用一个简单的setTimeout来解决这个问题,将addEventListener延迟1毫秒。

我修改后的代码是:

document.getElementsByTagName('button')[0].addEventListener('click', function(){
    // Both of the following will work now:

    //window.location = '#target';
    //document.getElementById('target').scrollIntoView();

    setTimeout(function(){
        window.addEventListener('scroll', function(){
            // Removes this function from the window's onscroll event so that it only triggers once
            this.removeEventListener('scroll', arguments.callee);
            alert('Triggered!');
        });
    }, 1);
});