2012-08-11 56 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);​