简体   繁体   中英

My scripts doesn't work on Mozilla Firefox but does on Chrome

I have a simple "Back to top" button coded in JS. When I scroll down 150px it shows on the bottom-right part of the page and when I click on this button it takes me back to the top of the page.

This works correctly on Google Chrome, but on Mozilla Firefox it does not.

I have a similar problem with another script that generates a random number from a user input.

first script on codepen:

(function(){

  function createButton() {

    var button = document.createElement("button");


    button.classList.add("backToTop", "hiddenBack");
    button.textContent = "back";
    document.body.appendChild(button);

    return button;
  }
  var button = createButton();

  function animatedScroll(){
    if(window.pageYOffset > 0){
      window.scrollBy(0, -5);
      setTimeout(animatedScroll, 10);
    }

  };

  button.addEventListener("click", function(e) {
      e.stopPropagation();
      animatedScroll();

   },false);

  window.addEventListener("scroll", function(e){

    if( window.pageYOffset >= 150){
      button.classList.remove("hiddenBack");
    }else {
      button.classList.add("hiddenBack");
    }

  },false);


})();

second script on codepen:

var btn = document.querySelector("#getNumbers"),
    output = document.querySelector("#showNumbers");

function getRandom(min, max) {
  return Math.round(Math.random() * (max - min) + min);
}

function showRandomNumber(){

  var numbers = [];
  var random,
  from = document.querySelector("#from").value,
  to = document.querySelector("#to").value,
  how = document.querySelector("#how").value;

  for(var i = 0; i < how; i++){

    random = getRandom(from,to);

    while(numbers.indexOf(random) !== -1){
      random = getRandom(from,to);
    }

  numbers.push(random)
  }

  output.value = numbers.join(", ");

}

btn.onclick = showRandomNumber;

Use the window.pageYOffset instead of document.body.scrollTop :

if(window.pageYOffset >= 150)

More detail on the issue here : document.body.scrollTop Firefox returns 0 : ONLY JS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM