javascript - 鼠标滚轮上的 JS scrollIntoView 功能不起作用
问题描述
我有上面的脚本,它在浏览器控制台上输出正确的 id,但不滚动:
var divID = null;
var up = null;
var down = null;
function div(x) {
switch(x.id) {
case 's1':
up = null;
down = 's2';
break;
case 's2':
up = 's1';
down = 's3'
break;
case 's3':
up = 's2';
down ='s4';
break;
case 's4':
up = 's3';
down = null;
break;
default:
up = null;
down = null;
break;
}
}
window.addEventListener('wheel', function(e) {
if (e.deltaY < 0 && up) {
console.log(up);
document.getElementById(up).scrollIntoView();
}
if (e.deltaY > 0 && down) {
console.log(down);
document.getElementById(down).scrollIntoView();
}
});
我正在使用这种结构:
<div id='s1' onmouseover="div(this)">
<!--content-->
</div>
<div id='s2' onmouseover="div(this)">
<!--content-->
</div>
<div id='s3' onmouseover="div(this)">
<!--content-->
</div>
<div id='s4' onmouseover="div(this)">
<!--content-->
</div>
正如我所说,console.log 打印它应该打印的内容,但滚动什么也不做,只是常规滚动。如果重要,我正在使用 wordpress。
解决方案
这里的问题是,在某些浏览器和操作系统中,滚动到一个元素不会激活该元素的悬停状态。此外,如果有人拖动滚动条,它永远不会激活您的悬停。
这里的悬停告诉你的滚动事件去哪里,但它们需要悬停动作才能生效。您最好使用它们的 offsetTop 值找到正确的元素,而不是在滚动期间需要第二个事件。
[编辑] 或者滚动事件的滚动覆盖了 scrollIntoView 方法的潜力。因为,您似乎只想进行滚动劫持运动,请尝试e.preventDefault()
在滚动事件中添加一个。
推荐阅读
- php - 模型关系在其他任何地方都可以正常工作,但是在广播方面我得到了 RelationNotFoundException
- reactjs - ReactJS - 用 chartJS-2 标记多维数组
- powershell - Powershell get-aduser 格式化 Write-Host
- javascript - 未找到外部依赖/回购
- gsm - 如何终止拨出 CSD 通话?
- node.js - 如何连接到 mongodb atlas 集群以使用节点 js 创建新数据库
- node.js - jsonwebtoken 在 nodejs 版本 10x 中返回 null
- python-3.x - 如何让 jupyter 脚本在 ubuntu 液滴上 24/7 全天候运行
- c# - 以静默模式运行可执行文件
- python - 如何从包含多个人名的电子邮件中提取发件人姓名?