我有这个 vue 模板,其中包含许多子组件,其中许多子组件使用 overflow-y
在内容过多时显示滚动条。
<div @wheel="onWheel">
...
</div>
对应的处理程序是:
onWheel: function (ev) {
//console.log(ev)
if (event.deltaY < 0) this.goto(-1)
else if (event.deltaY > 0) this.goto(+1)
},
即期望的行为是鼠标滚轮向上或向下移动数据库记录,除非它有更明显的事情要做。我的意思是,如果它位于带有滚动条的组件上,用户将期望鼠标滚轮在该组件内滚动,而不是更改数据库记录!
有办法做到这一点吗?我尝试添加 .self
:
<div @wheel.self="onWheel">
...
</div>
但这完全阻止了它的工作。
我想知道是否尝试拦截每个子组件中的轮子事件,但是(除了维护噩梦之外)我不确定这是否可能,因为它是一个特殊的事件( at least in Chrome ),您无法调用preventDefault()
开启。
通过查看 ev
可以看出,我从 ev.target
知道鼠标位于哪个元素上。我能以某种方式从那里找出它或任何父级是否显示滚动条吗?
最佳答案
好吧,您并不是想要preventDefault
,而是希望如果子组件有自己定义的,事件就不会冒泡到
事件。您可以使用以下方法执行此操作:父级
>wheel
event.stopPropagation();
<小时/>
代码沙箱:
我在这里创建了一个codesandbox演示:https://codesandbox.io/s/wheel-propagation-demo-cocnx
请务必打开演示中的控制台以查看不同的事件触发。
<小时/>代码示例:
App.vue
<template>
<div @wheel="onWheel" id="app">
<img width="25%" src="./assets/logo.png">
<Base msg="Hello Vue in CodeSandbox!">this is a test</Base>
</div>
</template>
<script>
import Base from "./components/Base";
export default {
name: "App",
components: {
Base
},
methods: {
onWheel: function(e) {
console.log("wheeling over " + e.currentTarget.id);
}
}
};
</script>
Base.vue
<template>
<div class="hello" style="margin-top: 30px; padding: 30px; background: beige;">
<slot></slot>
<Wheeler>wheel me!</Wheeler>
</div>
</template>
<script>
import Wheeler from "./Wheeler.vue";
export default {
components: {
Wheeler
},
name: "Base",
props: {
msg: String
}
};
</script>
Wheeler.vue
<template>
<div @wheel="otherWheel" class="wheelMe">
<slot></slot>
</div>
</template>
<script>
export default {
methods: {
otherWheel: function(e) {
console.log("wheeling over " + e.currentTarget.className);
e.currentTarget.style["background-color"] =
"rgb(" +
[
Math.floor(Math.random() * 254),
Math.floor(Math.random() * 254),
Math.floor(Math.random() * 254)
].toString() +
")";
e.stopPropagation();
}
}
};
</script>
<小时/>
注意:
如果您想阻止滚轮导致垂直滚动
发生,您可以单独处理该事件。
关于javascript - 如何判断滚轮事件是否发生在带有滚动条的元素上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58277154/