窗口宽度和滚动宽度值

Window width and scroll width values

本文关键字:滚动 窗口      更新时间:2023-11-02

当屏幕分辨率大于或等于1200px时,我想显示"返回顶部"按钮。当然,这取决于窗口宽度。这里是jQuery代码:

    var wW = $(window).width() + 17;
console.log(wW);
            if (wW >= 1200) {
                $(window).scroll(function () {
                    if ($(this).scrollTop() > 100) {
                        $('#oc-ontop').fadeIn('fast');
                    } else {
                        $('#oc-ontop').fadeOut('fast');
                    }
                });
            }

所以,若您将窗口宽度设置为1200px,控制台会显示值1200。但是1200是窗口宽度(1183px)+滚动条宽度(17px)的总和。如何在这个函数中计算滚动条的宽度,使其与宽度无关?

看看这个线程:我如何获得浏览器';s滚动条大小?

当你从那里应用代码时(最初是Alexandre Gomes博客):

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);
};

你可以写:

var wW = $(window).width() + getScrollBarWidth();