2012-08-11 59 views
0

在我的页面中,我希望检测页面是否具有垂直滚动条,如果需要,则需要检测滚动条的宽度,以便减少我的身体的宽度,从而防止我的边栏从查看非滚动页面到滚动页面的位置发生变化。 我有以下的jQuery/Javascript代码:检测垂直滚动和滚动条宽度并将宽度更改应用于主体

 $(document).ready(function() { 
     var parent, child, width; 

     if (width === undefined) { 
      parent = $('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo('body'); 
      child = parent.children(); 
      width = child.innerWidth() - child.height(99).innerWidth(); 
      parent.remove(); 
     } 

     if ($("body").height() > $(window).height()) { 
      //change width of body here 
     } 
    }); 

不幸的是,这个代码不为我工作。有人可以让我知道我要去哪里吗?

回答

0
(function($) { 
    $.fn.ScrollBarWidth = function() { 
     if (this.get(0).scrollHeight > this.height()) { //check if element has scrollbar 
      var inner = document.createElement('p'); 
      inner.style.width = "100%"; 
      inner.style.height = "200px"; 
      var outer = document.createElement('div'); 
      outer.style.position = "absolute"; 
      outer.style.top = "0px"; 
      outer.style.left = "0px"; 
      outer.style.visibility = "hidden"; 
      outer.style.width = "200px"; 
      outer.style.height = "150px"; 
      outer.style.overflow = "hidden"; 
      outer.appendChild(inner); 
      document.body.appendChild(outer); 
      var w1 = inner.offsetWidth; 
      outer.style.overflow = 'scroll'; 
      var w2 = inner.offsetWidth; 
      if (w1 == w2) w2 = outer.clientWidth; 
      document.body.removeChild(outer); 
      return (w1 - w2); 
     } 
    } 
})(jQuery); 

运行像这样:

var scrollbarWidth = $('body').ScrollBarWidth(); 
console.log(scrollbarWidth);​ //prints the scrollbar width to the console 

FIDDLE

0

你不应该需要改变body的宽度。默认情况下,它是窗口宽度的100%,并会在滚动条出现时进行调整。

但是,如果你不能因为某种原因将宽度设​​置为100%,先看看禁用水平滚动条可帮助您:

overflow-x: hidden; 

如果不削减,从使用功能here获取滚动条的宽度。然后,听window调整大小事件:

var $window = $(window), 
    $body = $('body'); 

function resize() { 
    if ($body.height() > $window.height()) { 
     $body.width($body.width() - getScrollBarWidth()); 
    } 
} 

$(window).resize(resize);​