javascript中的简单常量在我的函数中不起作用
我试图用常量简化我的代码,但它不起作用javascript中的简单常量在我的函数中不起作用,javascript,Javascript,我试图用常量简化我的代码,但它不起作用 // my const 'myscroll' is not working ?? Why ?? const myscroll = document.querySelector('.scrollup'); // When the user scrolls down 20px from the top of the document, show the button window.onscroll = function () {scrollFunction
// my const 'myscroll' is not working ?? Why ??
const myscroll = document.querySelector('.scrollup');
// 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 > 800 || document.documentElement.scrollTop > 800) {
myscroll.style.display = "block";
} else {
myscroll.style.display = "none";
}
};
我必须那样做
window.onscroll = function () {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 800 || document.documentElement.scrollTop > 800) {
document.querySelector('.scrollup').style.display = "block";
} else {
document.querySelector('.scrollup').style.display = "none";
}
};
这一定很简单,但我是瞎子!
谢谢你的帮助
constmyscroll=document.querySelector('.scrollup');
window.onscroll=滚动函数;
函数滚动函数(e){
const state=document.documentElement.scrollTop>200;
myscroll.style.display=状态?'block':'none';
};代码>
正文{
高度:500vh;
}
.向上滚动{
宽度:50px;
高度:50px;
位置:固定;
底部:10px;
右:10px;
背景色:红色;
边界半径:50%;
显示:无;
}
将常量myscroll=代码>在滚动函数中
这样它就不会在加载文档之前运行-就像你原来的那样。你能详细解释一下“不工作”是什么意思吗?你想做什么?请检查myscroll中是否有一些值,我想它应该是空的。如果为空,则在呈现html内容之前加载js。谢谢@MoloF,这种样式更好。但我还是有同样的问题。我必须这样做才能使它在localhost中工作:`const state=document.documentElement.scrollTop>400;document.querySelector('.scrollup')。style.display=state?“块':'无'`@Lo1176,我理解正确,您的本地机器有问题
?也许您先编写JS
代码,然后再编写html
?尝试将JS
添加到BODY
标记的最底部