[英]My scripts doesn't work on Mozilla Firefox but does on Chrome
I have a simple "Back to top" button coded in JS. 我有一个用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.
当我向下滚动150px时,它会显示在页面的右下角;当我单击此按钮时,它将带我回到页面的顶部。
This works correctly on Google Chrome, but on Mozilla Firefox it does not. 这在Google Chrome上可以正常运行,但在Mozilla Firefox上则不能。
I have a similar problem with another script that generates a random number from a user input. 我在另一个脚本中也遇到类似的问题,该脚本从用户输入生成随机数。
first script on codepen: 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: 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
: 使用
window.pageYOffset
而不是document.body.scrollTop
:
if(window.pageYOffset >= 150)
More detail on the issue here : document.body.scrollTop Firefox returns 0 : ONLY JS 有关此问题的更多详细信息,请访问: document.body.scrollTop Firefox返回0:仅JS
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.