当鼠标位于子可滚动HTML元素上时,如何使用鼠标滚轮移动父滚动条

How to move parent scroll bar with mouse wheel when mouse is over a child scrollable HTML element?

本文关键字:鼠标 何使用 移动 滚动条 滚动 元素 HTML      更新时间:2023-09-26

我有以下问题。我有父div,它包含几个子div。父级和子级都有滚动条。当鼠标位于父元素上时,我只想移动父元素的滚动条,无论鼠标是否悬停在可滚动的子div上。换句话说,我希望防止对子事件进行事件处理,并将事件传播给父事件。像这样:

<div id='parent' style='overflow-y:auto;height:200px;width:100%'>
    <div class='child' style='overflow-y:auto;height:100px'>
    </div>
    <div class='child' style='overflow-y:auto;height:100px'>
    </div>
    <div class='child' style='overflow-y:auto;height:100px'>
    </div>
</div>
<script>
    $('.child').bind('mousewheel DOMMouseScroll', function(e) {
        $(e.target).parent().trigger(e);
    });
</script>

这是正确的解决方案,感谢@DavidFregoli:

$('.child').on('mousewheel DOMMouseScroll', function(e) {
    var $div = $(this),
    $parent = $div.parent(),
    scrollAmount = 30,
    currentScroll = $parent.scrollTop(),
    newScroll = currentScroll + (e.originalEvent.wheelDelta < 0 ? scrollAmount : -scrollAmount);
    $parent.scrollTop(newScroll);
    return false;
});

全部代码在这里