我正在try 使一个按钮在HTML/JS中的工作方式与滚动鼠标滚轮或按箭头键浏览网页时的效果相同.我还没有找到任何方法来让这件事正常进行.我试过使用KeyboardEvent,当按钮模拟箭头键按钮时,网页可以识别,但它实际上并不像网页单击箭头键时那样滚动.我怀疑这可能是因为箭头键滚动功能可能是Web浏览器的一个功能,而不是网页的内置功能.ScllTo()也不起作用,因为它不是特定于元素的,因为HTML按钮始终固定在网页底部,以充当用户的屏幕导航按钮.实际上,我是在try 导航到当前视口中某个部分的上方或下方.以下是一个示例,演示了没有按钮功能的网页外观:
<!DOCTYPE html>
<html lang="en" style="scroll-snap-type: y mandatory;">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
section {
height: 100vh;
scroll-snap-align: start;
scroll-snap-stop: always;
}
button {
position: fixed;
bottom: 0;
margin: 5rem;
padding: 1rem;
}
</style>
</head>
<body>
<section style="background-color: lightsteelblue;">
<h1>Section 1</h1>
</section>
<section style="background-color: pink;">
<h1>Section 2</h1>
</section>
<section style="background-color: lightseagreen;">
<h1>Section 3</h1>
</section>
<button style="left:0">Down</button>
<button style="right:0">Up</button>
</body>
</html>
使用scllTo()并不起作用,因为(据我所知)它是特定的,所以我只能滚动到某个部分.
代码类似于:
const upArrow = document.getElementById('upButton');
upArrow.addEventListener('click', function() {
const arrowUpEvent = new KeyboardEvent('keydown', {
key: 'ArrowUp',
keyCode: 38,
which: 38,
bubbles: true,
});
document.dispatchEvent(arrowUpEvent);
});
也不起作用,因为虽然当运行addEventListener('keydown', function(event) {if (event.key === 'ArrowUp') {alert('Arrow Up key pressed!');
时我会收到alert ,但谷歌Chrome中箭头键的向下滚动功能不会发生.
我期待的是:当按下其中一个按钮时,网页会滚动到上面或下面的部分,或者如果没有部分,网页会根据按下的按钮向上或向下滚动少量.