【问题标题】:How To Get The Width of The Browsers Scrollbars And Add It To The Width of The Window Using JQuery? [duplicate]如何使用 JQuery 获取浏览器滚动条的宽度并将其添加到窗口的宽度? [复制]
【发布时间】:2016-03-29 07:48:11
【问题描述】:

我正在尝试找出用户可能正在使用的浏览器(例如 Edge、Firefox、Opera、Chrome 等)滚动条的宽度(如果存在滚动条)并将其添加到窗口的宽度,以便我的 JQuery 代码与我的 CSS 代码对齐,以便在调整浏览器大小时我可以确定窗口的宽度,但不能确定滚动条。

jQuery

$(window).on('resize',function(){
    if($(this).width() > 680){
        //add remove css styles
    }
});

【问题讨论】:

标签: jquery html css


【解决方案1】:

你可以使用这个函数来获取它:

function getScrollBarWidth () {
  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);
};

希望对你有帮助……

【讨论】:

    【解决方案2】:

    如果有人有更好的解决方案或可以改进此代码,我想出了一种似乎对我有用的方法,请告诉我。

    $(window).on('resize',function(){
        //get accurate width of the screen by removing scrollbars
        $('html, body').css('overflow', 'hidden');
        var w = $(window).width();
    
        //add back the scrollbars
        $('html, body').css('overflow', 'visible');
        if(w > 680){
            //add more code here what you need done when screen reaches desired size
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2013-11-04
      • 2012-02-06
      • 1970-01-01
      • 2013-10-10
      • 2013-06-15
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 2016-12-01
      相关资源
      最近更新 更多