Block Mouse Scroll inside DIV

假装没事ソ 提交于 2019-12-23 03:41:54

问题


How to block mouse scroll in a div with id="slider-'.$question_id.'"

So basically if you put mouse over that div, click it you will not be able to scroll using mouse scroll.

<div id="slider-'.$question_id.'"> CONTENT </div>

I am only looking for solution with JavaScript

I have code below, but this is blocking whole page:

<script type='text/javascript'>
document.onmousewheel = function(){ stopWheel(); } /* IE7, IE8 */
if(document.addEventListener){ /* Chrome, Safari, Firefox */
    document.addEventListener('DOMMouseScroll', stopWheel, false);
}

function stopWheel(e){
    if(!e){ e = window.event; } /* IE7, IE8, Chrome, Safari */
    if(e.preventDefault) { e.preventDefault(); } /* Chrome, Safari, Firefox */
    e.returnValue = false; /* IE7, IE8 */
}
</script>

回答1:


You can use event.target to identify if the scrolling element is the one you want to affect:

function stopWheel(e){
    if (e.target.id === "slider-'.$question_id.'") {
        if(!e){ e = window.event; } /* IE7, IE8, Chrome, Safari */
        if(e.preventDefault) { e.preventDefault(); } /* Chrome, Safari, Firefox */
        e.returnValue = false; /* IE7, IE8 */
    }
}  

Plus you need to provide the event in the first call:

document.onmousewheel = function (e) {
    stopWheel(e);
} /* IE7, IE8 */

Here's an example: http://jsfiddle.net/Da3L3/




回答2:


You need to target the div so you can try something like :

document.getElementByID("slider-'.$question_id.'").onmousewheel = function(){ stopWheel(); } /* IE7, IE8 */
if(document.getElementByID("slider-'.$question_id.'").addEventListener){ /* Chrome, Safari, Firefox */
    document.getElementByID("slider-'.$question_id.'").addEventListener('DOMMouseScroll', stopWheel, false);
}

Hope i help



来源:https://stackoverflow.com/questions/23389689/block-mouse-scroll-inside-div

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