这2个windows.onscroll javascript代码无法一起使用

时间:2019-10-14 16:47:34

标签: javascript

我不是JavaScript专家。我有这两个代码不能同时工作。我不知道为什么,我问你问题可能在哪里?

// This is the first part 

//Get the button
var mybutton = document.getElementById("scrollToTop");
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
  scrollFunction()
};

function scrollFunction() {
  if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {
    mybutton.style.display = "block";
  } else {
    mybutton.style.display = "none";
  }
}
// When the user clicks on the button, scroll to the top of the document
function toTopFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}

// When the user scrolls the page, execute myFunction
window.onscroll = function() {
  myFunction()
};


// This is the second part   

function myFunction() {
  var winScroll = document.body.scrollTop || document.documentElement.scrollTop;
  var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
  var scrolled = (winScroll / height) * 100;
  document.getElementById("myBar").style.width = scrolled + "%";
}

感谢任何人

1 个答案:

答案 0 :(得分:2)

每次分配给window.onscroll时,它都会替换之前的分配。

如果要使用多个事件侦听器,请使用addEventListener()

window.addEventListener("scroll", scrollFunction);
window.addEventListener("scroll", myFunction);

或在单个处理程序中调用两个函数:

window.onscroll = function() {
    scrollFunction();
    myFunction();
};