最新消息:专注互联网,专注前端,多分享,多学习!

获取浏览器滚动条宽度方法

scrollbars

以下是获取浏览器滚动条宽度方法:

<html>
<head>
<title>Test - scroll bar width</title>
</head>
<body>
<h1>scroll bar width</h1>
<div style="overflow:scroll; width:320px; height:240px; background-color:#eeeeee;"></div>
<div id="output">

</div>
<script type="text/javascript">
             var __scrollBarWidth = null;
             function getScrollBarWidth() {
                 if (__scrollBarWidth) return __scrollBarWidth;

                 var scrollBarHelper = document.createElement("div");
                 // if MSIE
                 // 如此设置的话,scroll bar的最大宽度不能大于0px(通常不会)。
                 scrollBarHelper.style.cssText = "overflow:scroll;width:100px;height:100px;"; 
                 // else OTHER Browsers:
                 // scrollBarHelper.style.cssText = "overflow:scroll;";
                document.body.appendChild(scrollBarHelper);
                 if (scrollBarHelper) {
                     __scrollBarWidth = {
                         horizontal: scrollBarHelper.offsetHeight - scrollBarHelper.clientHeight,
                         vertical: scrollBarHelper.offsetWidth - scrollBarHelper.clientWidth
                     };
                 }
                 document.body.removeChild(scrollBarHelper);
                 return __scrollBarWidth;
             }
             function test() {
                 var scrollBarWidth = getScrollBarWidth();
                 document.getElementById("output").innerHTML += "scroll bar width : horizontal : " + scrollBarWidth.horizontal
                  + " vertical : " + scrollBarWidth.vertical + "<br />";
             }
             test();
</script>
</body>
</html>

再来一种方法

getScrollBarHW : function () { //获取浏览器的宽度和高度对象
            if (this.scrollBarHW) {
                return this.scrollBarHW;
            }
            var div = document.createElement('div');
            div.style.overflow = 'scroll';
            div.style.visibility = 'hidden';
            div.style.position = 'absolute';
            div.style.width = '100px';
            div.style.height = '100px';
            //div.style.cssText = 'overflow:scroll;width:100px;height:100px;';
            document.body.appendChild(div);

            this.scrollBarHW = {
                width : div.offsetWidth - div.clientWidth,
                height : div.offsetHeight - div.clientHeight
            };
            div.parentNode.removeChild(div);
            return this.scrollBarHW;
        }

 

转载请注明:圆点网 » 获取浏览器滚动条宽度方法

与本文相关文章

网友评论

  1. 无意间发现的网站 很不错 挺喜欢的

    食谱大全2015-01-13 10:23