我想用鼠标水平滚动图标。我在Javascript中用scrollLeft尝试过,但滚动时该值不会改变。滚动时,只有 deltaY 值在 100 和 -100 之间变化。
有人知道问题出在哪里吗?
当我滚动并且鼠标悬停在滚动条上时,它可以工作,但我希望它可以在整个 div 容器上工作。如果可能的话,我也想在没有依赖项/npm-libraries 的情况下执行此操作。
<div class="icons flex_center_h flex_between">
<div class="flex_center_h flex_start instIconContainer"
@wheel="ScrollIcons($event)">
<FilterIcon
v-for="(icon, iconIndex) in rooms[index].description.icons"
:key="icon"
:icon="rooms[index].description.icons[iconIndex].icon"
:customClass="'instIcon'" />
</div>
<FilterIcon :customClass="'navIcon'" :icon="'nav'" />
</div>
import {
FilterIcon
} from '@/components/Elements/'
export default {
components: {
FilterIcon,
},
computed: {
rooms() {
return this.$store.state.rooms
}
},
methods: {
ScrollIcons(event) {
event.preventDefault()
event.target.scrollLeft += event.deltaY
console.log([event.deltaY, event.target.scrollLeft])
}
}
}
.icons
background: $bg
width: 80%
padding: 0.5rem 0.5rem
::-webkit-scrollbar
width: $scrollbarSize
height: 0.3rem
background: $bg-glow
border-radius: $radius_1
::-webkit-scrollbar-thumb
background: $purple
border-radius: $radius_1
.instIconContainer
width: 70%
max-width: calc(40px * 4)
max-height: 80px
overflow-x: auto
.instIcon
width: $IconSize
height: $IconSize
min-width: $IconSize
min-height: $IconSize
path, circle
fill: $purple
[100, 0]
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您的示例的问题是
event.target不是滚动条元素,而是图标。使用
ref确保您定位到正确的元素。 1另一个选项是绑定到元素的
scrollLeftHTML 属性并让 Vue 处理 DOM 更新。您只需更改控制器中的值。我们使用
.camel修饰符来绕过 HTML 属性(我们用来绑定到属性的属性)不区分大小写的事实:scroll-left.camel2, 3const { createApp, onMounted, reactive, toRefs } = Vue; const { min, max } = Math; createApp({ setup: () => { const state = reactive({ scroller: null, scrollLeft: 0, }); const onWheel = (e) => { state.scrollLeft = state.scroller ? min( state.scroller.scrollWidth - state.scroller.offsetWidth, max(0, e.deltaY + state.scrollLeft) ) : state.scrollLeft; }; return { ...toRefs(state), onWheel }; }, }).mount("#app");#app div span { min-width: 50%; display: inline-block; } #app div { display: flex; overflow-x: auto; cursor: ew-resize; }注释:
1 - 因为我们绑定到
scrollLeft属性,所以我们不需要ref不再。我保留它是因为我想将控制器scrollLeft值限制在有效值内,并且需要ref来计算最大值。2 - 从技术上讲,它应该是
:scroll-left.camel.prop,因为它是一个 HTML 属性,但是它也可以在没有.prop修饰符的情况下工作3 -
.scroll-left.camel也适用(:scroll-left.camel 的简写.prop)。我尝试了与您类似的方法,但直到我在
event.target.scrollLeft += event.deltaY 中使用在您的 ScrollIcons 方法中。这样,当您在光标悬停在图标上时使用鼠标滚轮时,您将定位到包含的 div 或标签,而不是定位到图标。换句话说,只要您的光标位于包含的 div 和鼠标滚轮中,该 div 就应该做出响应,而不管 div 和鼠标光标之间的任何其他元素如何。currentTarget而不是target时才起作用