Javascript 默认情况下,使用空格键使主体内的容器可滚动
我的代码中有以下标记:Javascript 默认情况下,使用空格键使主体内的容器可滚动,javascript,html,Javascript,Html,我的代码中有以下标记: <html> <body> <div class="page"> <div class="content"> ... </div> </div> </body> </html> 虽然这看起来有点奇怪,但它解决了
<html>
<body>
<div class="page">
<div class="content">
...
</div>
</div>
</body>
</html>
虽然这看起来有点奇怪,但它解决了我的应用程序的一些关键问题。无论如何,其思想是.content
容器是保存溢出内容的容器。无论如何,当第一次加载页面时,许多用户更喜欢使用空格键进行滚动。由于主体不可滚动,因此不会发生任何事情
默认情况下,如何更改空格键的目标以滚动.content
容器而不是正文?我尝试了以下方法:
html,
body {
position: absolute;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
left: 0;
top: 0;
}
.page {
position: absolute;
height: 100%;
width: 100%;
overflow: hidden;
}
.content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100%;
overflow: auto;
}
document.activeElement = document.getElementsByClassName("content")[0]
然而,这并没有起作用。谢谢您的帮助。这是您的解决方案:
对于css:
html,body
{
position: absolute;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
left: 0;
top: 0;
overflow: hidden; // i changed this line
}
.page {
position: absolute;
height: 100%;
width: 100%;
overflow: hidden;
}
.content {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100%;
overflow: scroll; // i changed this line
}
对于JavaScript:
// you can use getElementById if your element is unique in the page.
let container = document.getElementsByClassName('content')[0];
container.scrollTop = 40; // to set how much pixels you have to scroll
window.addEventListener('keydown',function(e){
e.preventDefault(); // to prevent the default spacebar event.
if(e.code === 'Space'){
container.scrollBy(0,container.scrollTop);
}
});