javascript - 默认情况下使用空格键使主体内的容器可滚动
问题描述
我的代码中有以下标记:
<html>
<body>
<div class="page">
<div class="content">
...
</div>
</div>
</body>
</html>
在我的 CSS 代码中,我有以下内容:
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;
}
虽然这看起来有点奇怪,但它为我的应用程序解决了一些关键问题。无论如何,这个想法是.content
容器是容纳溢出内容的容器。无论如何,当页面第一次加载时,很多用户更喜欢使用空格键来滚动。由于正文不可滚动,因此没有任何反应。
如何更改空格键的目标.content
以默认滚动容器而不是正文?我尝试了以下方法:
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);
}
});
推荐阅读
- docker - 让我们在 nginx docker 容器中加密
- angular - 如何在组件中等待服务 HTTP 调用完成
- python - ValueError:没有足够的值来解包 - 重命名文件
- android - Proguard 正在干扰请求 POJO 的字段名称 - 使用什么规则?
- java - 错误:无法为最终变量字符名赋值:this.characterName = characterName;
- database - 如何通过命令行在 Firefox 中添加或删除书签标签?
- android - 如何/在哪里保留私有 JSON 文件并将其捆绑在我的应用程序中?
- unified-service-desk - Microsoft USD,从 c# 单击按钮后为托管控件打开一个新选项卡
- python - 打印可能存在或不存在的嵌套字典值
- nginx - 用于从现有短链接 Web 服务创建短链接服务的 NGINX 配置