How to disable scrollbars with JavaScript?

2019-06-24 04:15发布

问题:

I need to lock the browser scrollbars when I show a div that represent a modal window in Internet Explorer 7 only. Googling I found that I can use document.body.style.overflow='hidden' but this doesn't work for IE7. I also tried with document.body.scroll="no" which works but only after I mouse over the scrollbar :-S

Does anybody knows a better aproach?

Thansks

回答1:

To answer your various questions (including that in your other comment), I think you're using the wrong positioning method.

Try position:fixed. It's basically the same as position:absolute apart from it's relative to the absolute viewport. Ie: if the user scrolls, the item stays in the same place on the screen.

So with this in mind, you can lay out a position:fixed overlay. Within that you can have your position:absolute (or fixed again, if you prefer -- it shouldn't make a difference) modal box.



回答2:

Set your modal overlay div to fill the body, so even if they scroll there's nothing they can do because everything is hidden underneath it.



回答3:

you can also hide scrollbars by using overflow:hidden so the user wont see the scollbars so it wont get tempted to scoll around:)



回答4:

This can help you:

documentOBJ = {
    /*Width and Height of the avaible viewport, what you'r seeing*/
    window : {
        x : function(){return (document.documentElement && document.documentElement.clientWidth) || window.innerWidth || self.innerWidth || document.body.clientWidth; },
        y : function(){return (document.documentElement && document.documentElement.clientHeight) || window.innerHeight || self.innerHeight || document.body.clientHeight;}
    },

    /*Scroll offset*/ 
    scroll : {
        x : function(){return ( document.documentElement && document.documentElement.scrollLeft) || window.pageXOffset || self.pageXOffset || document.body.scrollLeft; },
        y : function(){return ( document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop; }
    },

    /*Height and width of the total of the xhtml in a page*/
    page : {
        x : function(){return (document.documentElement && document.documentElement.scrollWidth) ? document.documentElement.scrollWidth : (document.body.scrollWidth > document.body.offsetWidth) ? document.body.scrollWidth : document.body.offsetWidth; },
        y : function(){return (document.documentElement && document.documentElement.scrollHeight) ? document.documentElement.scrollHeight : (document.body.scrollHeight > document.body.offsetHeight) ? document.body.scrollHeight : document.body.offsetHeight; }
    },
    pointer : {}
}