Mouse wheel scroll event

我与影子孤独终老i 提交于 2019-12-13 02:54:43

问题


What I want is : when mouse points on a div, page's scroll bar doesn't scroll. Is this impossible? When I do this, the page's scroll bar always scrolls. Here is a piece of the javascript code:

if(document.addEventListener){
    document.addEventListener('DOMMouseScroll',scrollFunc,false);
}
window.onmousewheel=document.onmousewheel=scrollFunc;//IE/Opera/Chrome/Safari

How to do that?


回答1:


Here you go:

var noscroll = document.getElementById('noscroll');

var locked, lockedX, lockedY;
noscroll.addEventListener('mouseover', function (){
    locked = true;
    lockedX = window.scrollX;
    lockedY = window.scrollY;
}, false);
noscroll.addEventListener('mouseout', function (){
    locked = false;
}, false);

window.addEventListener('scroll', function (e){
    if(locked === true){
        window.scrollTo(lockedX, lockedY);
        e.preventDefault();
    }
}, false);

Change the variable noscroll to whichever element you don't want to allow scrolling on.

Demo




回答2:


You can basically achieve it through css by specifying width, height and overflow properties for your div:

<div style="width:100px; height:100px; overflow: auto;" >
    text text text text text text text text text
    text text text text text text text text text
    text text text text text text text text text
    text text text text text text text text text
    text text text text text text text text text
    text text text text text text text text text
    text text text text text text text text text
    text text text text text text text text text
</div>


来源:https://stackoverflow.com/questions/14051908/mouse-wheel-scroll-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!