1

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?

Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140
Bruce Li
  • 137
  • 4
  • 13

2 Answers2

4

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

Some Guy
  • 15,854
  • 10
  • 58
  • 67
  • Thanks,this is very helpful for me.But there is another question,it's when I scoll the mouse wheel on the div,the page's scoll bar always first down and then up,in a word,the page has a kind of sloshing effect.I'm trying to resolve it,thank you again for you answer. – Bruce Li Dec 28 '12 at 01:05
  • @BruceLi Yeah, I see that happening in some browsers too, but i don't think there is anything we can do about it, since a scroll event is not cancelable – Some Guy Dec 28 '12 at 12:07
0

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>
Eli
  • 14,779
  • 5
  • 59
  • 77
  • I used the coordinate,like this:document.getElementById("svglocation").onmouseenter = function(event){ var x=event.clientX; var y=event.clientY; var div = document.getElementById("svglocation"); var divx1 = div.offsetLeft; var divy1 = div.offsetTop; var divx2 = div.offsetLeft + div.offsetWidth; var divy2 = div.offsetTop + div.offsetHeight; if( x > divx1 && x < divx2 && y > divy1 && y < divy2) { moenter(); }; }; – Bruce Li Dec 27 '12 at 09:02