Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/451.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
javascript中的简单常量在我的函数中不起作用_Javascript - Fatal编程技术网

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
标记的最底部