无法删除 Javascript 上的事件侦听器

Cannot remove eventlistener on Javascript

我有这样的功能:

if (localStorage.wsttoc_stat === undefined) { localStorage.wsttoc_stat = "Stop"; }

function ScrollToTop()
{
    var elem = document.querySelector('.elementclass');
    var scroll_height = elem.scrollTop;
    var scroll_offset = elem.offsetTop;

    function gotoTop()
    {
      if(scroll_height > scroll_offset)
      {
        setTimeout(function(){
          elem.scrollTop = scroll_offset;
        }, 1000);
        setTimeout(function(){
          elem.scroll_height = elem.scrollTop;
        }, 2000);
      }
    }

    console.log(localStorage.wsttoc_stat);
    if(localStorage.wsttoc_stat == "Scrolling")
    {

      localStorage.wsttoc_stat = 'Stop';
      console.log(localStorage.wsttoc_stat);
      elem.removeEventListener('scroll', gotoTop);

    } else {

      localStorage.wsttoc_stat = "Scrolling";
      console.log(localStorage.wsttoc_stat);
      elem.addEventListener('scroll', gotoTop);
      gotoTop();
    }
}

document.querySelector('#elementid').addEventListener('click', function(){ ScrollToTop(); });

该功能是通过点击一个按钮来执行的。 它已经是 运行 但当我单击按钮停止时它一直在滚动。

请问哪里错了?

刚刚

document.querySelector('#elementid').addEventListener('click', ScrollToTop);

gotoTop 的引用已更改,因为每次调用 ScrollToTop 时,它都会创建一个新的 gotoTop 函数。这就是为什么 removeEventListener 不是您所期望的。尝试像这样更改您的代码:

if (localStorage.wsttoc_stat === undefined) {
    localStorage.wsttoc_stat = "Stop";
}

function gotoTop() {
    var elem = document.querySelector('.elementclass');
    var scroll_height = elem.scrollTop;
    var scroll_offset = elem.offsetTop;
    if (scroll_height > scroll_offset) {
        setTimeout(function() {
            elem.scrollTop = scroll_offset;
        }, 1000);
        setTimeout(function() {
            elem.scroll_height = elem.scrollTop;
        }, 2000);
    }
}

function ScrollToTop() {
    var elem = document.querySelector('.elementclass');
    console.log(localStorage.wsttoc_stat);
    if (localStorage.wsttoc_stat == "Scrolling") {
        localStorage.wsttoc_stat = 'Stop';
        console.log(localStorage.wsttoc_stat);
        elem.removeEventListener('scroll', gotoTop);

    } else {
        localStorage.wsttoc_stat = "Scrolling";
        console.log(localStorage.wsttoc_stat);
        elem.addEventListener('scroll', gotoTop);
        gotoTop();
    }
}

document.querySelector('#elementid').addEventListener('click', function() {
    ScrollToTop();
});