检测页面是否有垂直滚动条?

时间:2022-11-25 18:15:02

I just want some simple JQ/JS to check if the current page/window (not a particular element) has a vertical scrollbar.

我只想要一些简单的JQ/JS来检查当前页面/窗口(不是特定的元素)是否具有垂直滚动条。

Googling gives me stuff that seems overly complex for just this basic feature.

Googling给我的东西似乎过于复杂,只适合这个基本功能。

How can this be done?

怎么做呢?

11 个解决方案

#1


83  

$(document).ready(function() {
    // Check if body height is higher than window height :)
    if ($("body").height() > $(window).height()) {
        alert("Vertical Scrollbar! D:");
    }

    // Check if body width is higher than window width :)
    if ($("body").width() > $(window).width()) {
        alert("Horizontal Scrollbar! D:<");
    }
});

#2


66  

try this:

试试这个:

var hasVScroll = document.body.scrollHeight > document.body.clientHeight;

This will only tell you if the vertical scrollHeight is bigger than the height of the viewable content, however. The hasVScroll variable will contain true or false.

不过,这只会告诉您垂直滚动高度是否大于可查看内容的高度。hasVScroll变量将包含true或false。

If you need to do a more thorough check, add the following to the code above:

如果您需要进行更彻底的检查,请在上面的代码中添加以下内容:

// Get the computed style of the body element
var cStyle = document.body.currentStyle||window.getComputedStyle(document.body, "");

// Check the overflow and overflowY properties for "auto" and "visible" values
hasVScroll = cStyle.overflow == "visible" 
             || cStyle.overflowY == "visible"
             || (hasVScroll && cStyle.overflow == "auto")
             || (hasVScroll && cStyle.overflowY == "auto");

#3


40  

I tried the previous answer and doesn't seem to be working the $("body").height() does not necessarily represent the whole html height.

我尝试了前面的答案,似乎并没有使用$(“body”)。height()并不一定代表整个html高度。

I have corrected the solution as follows:

我对解决方案做了如下修正:

// Check if body height is higher than window height :) 
if ($(document).height() > $(window).height()) { 
    alert("Vertical Scrollbar! D:"); 
} 

// Check if body width is higher than window width :) 
if ($(document).width() > $(window).width()) { 
    alert("Horizontal Scrollbar! D:<"); 
} 

#4


15  

Let's bring this question back from the dead ;) There is a reason Google doesn't give you a simple solution. Special cases and browser quirks affect the calculation, and it is not as trivial as it seems to be.

让我们把这个问题从死亡中带回来;谷歌没有给你一个简单的解决方案是有原因的。特殊情况和浏览器的怪癖会影响计算,而且它并不像看起来那么简单。

Unfortunately, there are problems with the solutions outlined here so far. I don't mean to disparage them at all - they are great starting points and touch on all the key properties needed for a more robust approach. But I wouldn't recommend copying and pasting the code from any of the other answers because

不幸的是,到目前为止,这里列出的解决方案存在一些问题。我并不是要贬低它们——它们是很好的起点,可以触及更健壮的方法所需的所有关键属性。但是我不建议从其他答案中复制和粘贴代码,因为

  • they don't capture the effect of positioned content in a way that is reliable cross-browser. The answers which are based on body size miss this entirely (the body is not the offset parent of such content unless it is positioned itself). And those answers checking $( document ).width() and .height() fall prey to jQuery's buggy detection of document size.
  • 它们不会以一种可靠的跨浏览器方式捕捉定位内容的效果。基于身体大小的答案完全忽略了这一点(除非身体本身被定位,否则它不是这些内容的偏移父元素)。并且这些答案检查$(document).width()和.height()是jQuery对文档大小的bug检测的结果。
  • Relying on window.innerWidth, if the browser supports it, makes your code fail to detect scroll bars in mobile browsers, where the width of the scroll bar is generally 0. They are just shown temporarily as an overlay and don't take up space in the document. Zooming on mobile also becomes a problem that way (long story).
  • 依靠窗口。如果浏览器支持innerWidth,则会使代码无法检测到移动浏览器中的滚动条,在移动浏览器中,滚动条的宽度通常为0。它们只是临时显示为一个覆盖层,不占用文档中的空间。移动移动也成为一个问题(长故事)。
  • The detection can be thrown off when people explicitly set the overflow of both the html and body element to non-default values (what happens then is a little involved - see this description).
  • 当人们显式地将html和body元素的溢出值设置为非默认值时(这时发生的情况有点复杂——请参阅本文的描述),可以取消检测。
  • In most answers, body padding, borders or margins are not detected and distort the results.
  • 在大多数答案中,没有检测到正文填充、边框或边距并扭曲结果。

I have spent more time than I would have imagined on a finding a solution that "just works" (cough). The algorithm I have come up with is now part of a plugin, jQuery.isInView, which exposes a .hasScrollbar method. Have a look at the source if you wish.

我花了比我想象中更多的时间去寻找一个“有效”的解决方案(咳嗽)。我想到的算法现在是jQuery插件的一部分。提供了一个. hasscrollbar方法。如果你愿意的话,可以看看它的出处。

In a scenario where you are in full control of the page and don't have to deal with unknown CSS, using a plugin may be overkill - after all, you know which edge cases apply, and which don't. However, if you need reliable results in an unknown environment, then I don't think the solutions outlined here will be enough. You are better off using a well-tested plugin - mine or anybody elses.

在一个你完全控制页面并且不需要处理未知CSS的场景中,使用一个插件可能有点过头了——毕竟,你知道哪些边情况适用,哪些不适用。然而,如果您需要在未知环境中得到可靠的结果,那么我认为这里列出的解决方案是不够的。你最好使用一个测试良好的插件——我的或者其他的。

#5


14  

This one did works for me:

这个方法对我确实有效:

function hasVerticalScroll(node){
    if(node == undefined){
        if(window.innerHeight){
            return document.body.offsetHeight> window.innerHeight;
        }
        else {
            return  document.documentElement.scrollHeight > 
                document.documentElement.offsetHeight ||
                document.body.scrollHeight>document.body.offsetHeight;
        }
    }
    else {
        return node.scrollHeight> node.offsetHeight;
    }
}

For the body, just use hasVerticalScroll().

对于主体,只需使用hasVerticalScroll()。

#6


9  

var hasScrollbar = window.innerWidth > document.documentElement.clientWidth;

#7


2  

I found vanila solution

我发现香草香精的解决方案

var hasScrollbar = function() {
  // The Modern solution
  if (typeof window.innerWidth === 'number')
    return window.innerWidth > document.documentElement.clientWidth

  // rootElem for quirksmode
  var rootElem = document.documentElement || document.body

  // Check overflow style property on body for fauxscrollbars
  var overflowStyle

  if (typeof rootElem.currentStyle !== 'undefined')
    overflowStyle = rootElem.currentStyle.overflow

  overflowStyle = overflowStyle || window.getComputedStyle(rootElem, '').overflow

    // Also need to check the Y axis overflow
  var overflowYStyle

  if (typeof rootElem.currentStyle !== 'undefined')
    overflowYStyle = rootElem.currentStyle.overflowY

  overflowYStyle = overflowYStyle || window.getComputedStyle(rootElem, '').overflowY

  var contentOverflows = rootElem.scrollHeight > rootElem.clientHeight
  var overflowShown    = /^(visible|auto)$/.test(overflowStyle) || /^(visible|auto)$/.test(overflowYStyle)
  var alwaysShowScroll = overflowStyle === 'scroll' || overflowYStyle === 'scroll'

  return (contentOverflows && overflowShown) || (alwaysShowScroll)
}

#8


2  

Oddly none of these solutions tell you if a page has a vertical scrollbar.

奇怪的是,这些解决方案都不能告诉您页面是否具有垂直滚动条。

window.innerWidth - document.body.clientWidth will give you the width of the scrollbar. This should work in anything IE9+ (not tested in the lesser browsers). (Or to strictly answer the question, !!(window.innerWidth - document.body.clientWidth)

窗口。innerWidth——document.body。clientWidth将为您提供滚动条的宽度。这应该适用于任何IE9+(未在较小的浏览器中测试)。或者严格地回答这个问题,!!innerWidth - document.body.clientWidth)

Why? Let's say you have a page where the content is taller than the window height and the user can scroll up/down. If you're using Chrome on a Mac with no mouse plugged in, the user will not see a scrollbar. Plug a mouse in and a scrollbar will appear. (Note this behaviour can be overridden, but that's the default AFAIK).

为什么?假设你有一个页面,内容比窗口高,用户可以向上/向下滚动。如果你在没有鼠标插入的Mac电脑上使用Chrome,用户将看不到滚动条。插入鼠标,滚动条就会出现。(注意这个行为可以被重写,但这是默认的AFAIK)。

#9


2  

    <script>
    var scrollHeight = document.body.scrollHeight;
    var clientHeight = document.documentElement.clientHeight;
    var hasVerticalScrollbar = scrollHeight > clientHeight;

    alert(scrollHeight + " and " + clientHeight); //for checking / debugging.
    alert("hasVerticalScrollbar is " + hasVerticalScrollbar + "."); //for checking / debugging.
    </script>

This one will tell you if you have a scrollbar or not. I've included some information that may help with debugging, which will display as a JavaScript alert.

这个会告诉你你是否有滚动条。我已经包含了一些可能有助于调试的信息,这些信息将作为JavaScript警报显示。

Put this in a script tag, after the closing body tag.

在结束主体标记之后,将其放入脚本标记中。

#10


0  

Other solutions didn't work in one of my projects and I've ending up checking overflow css property

其他解决方案在我的一个项目中不起作用,我最后检查了overflow css属性

function haveScrollbar() {
    var style = window.getComputedStyle(document.body);
    return style["overflow-y"] != "hidden";
}

but it will only work if scrollbar appear disappear by changing the prop it will not work if the content is equal or smaller than the window.

但是,只有当滚动条通过改变支柱出现消失时,它才会工作,如果内容等于或小于窗口,它就不会工作。

#11


0  

I wrote an updated version of Kees C. Bakker's answer:

我写了更新版的Kees C. Bakker的回答:

const hasVerticalScroll = (node) => {
  if (!node) {
    if (window.innerHeight) {
      return document.body.offsetHeight > window.innerHeight
    }
    return (document.documentElement.scrollHeight > document.documentElement.offsetHeight)
      || (document.body.scrollHeight > document.body.offsetHeight)
  }
  return node.scrollHeight > node.offsetHeight
}

if (hasVerticalScroll(document.querySelector('body'))) {
  this.props.handleDisableDownScrollerButton()
}

The function returns true or false depending whether the page has a vertical scrollbar or not.

函数返回true或false,这取决于页面是否具有垂直滚动条。

For example:

例如:

const hasVScroll = hasVerticalScroll(document.querySelector('body'))

if (hasVScroll) {
  console.log('HAS SCROLL', hasVScroll)
}

#1


83  

$(document).ready(function() {
    // Check if body height is higher than window height :)
    if ($("body").height() > $(window).height()) {
        alert("Vertical Scrollbar! D:");
    }

    // Check if body width is higher than window width :)
    if ($("body").width() > $(window).width()) {
        alert("Horizontal Scrollbar! D:<");
    }
});

#2


66  

try this:

试试这个:

var hasVScroll = document.body.scrollHeight > document.body.clientHeight;

This will only tell you if the vertical scrollHeight is bigger than the height of the viewable content, however. The hasVScroll variable will contain true or false.

不过,这只会告诉您垂直滚动高度是否大于可查看内容的高度。hasVScroll变量将包含true或false。

If you need to do a more thorough check, add the following to the code above:

如果您需要进行更彻底的检查,请在上面的代码中添加以下内容:

// Get the computed style of the body element
var cStyle = document.body.currentStyle||window.getComputedStyle(document.body, "");

// Check the overflow and overflowY properties for "auto" and "visible" values
hasVScroll = cStyle.overflow == "visible" 
             || cStyle.overflowY == "visible"
             || (hasVScroll && cStyle.overflow == "auto")
             || (hasVScroll && cStyle.overflowY == "auto");

#3


40  

I tried the previous answer and doesn't seem to be working the $("body").height() does not necessarily represent the whole html height.

我尝试了前面的答案,似乎并没有使用$(“body”)。height()并不一定代表整个html高度。

I have corrected the solution as follows:

我对解决方案做了如下修正:

// Check if body height is higher than window height :) 
if ($(document).height() > $(window).height()) { 
    alert("Vertical Scrollbar! D:"); 
} 

// Check if body width is higher than window width :) 
if ($(document).width() > $(window).width()) { 
    alert("Horizontal Scrollbar! D:<"); 
} 

#4


15  

Let's bring this question back from the dead ;) There is a reason Google doesn't give you a simple solution. Special cases and browser quirks affect the calculation, and it is not as trivial as it seems to be.

让我们把这个问题从死亡中带回来;谷歌没有给你一个简单的解决方案是有原因的。特殊情况和浏览器的怪癖会影响计算,而且它并不像看起来那么简单。

Unfortunately, there are problems with the solutions outlined here so far. I don't mean to disparage them at all - they are great starting points and touch on all the key properties needed for a more robust approach. But I wouldn't recommend copying and pasting the code from any of the other answers because

不幸的是,到目前为止,这里列出的解决方案存在一些问题。我并不是要贬低它们——它们是很好的起点,可以触及更健壮的方法所需的所有关键属性。但是我不建议从其他答案中复制和粘贴代码,因为

  • they don't capture the effect of positioned content in a way that is reliable cross-browser. The answers which are based on body size miss this entirely (the body is not the offset parent of such content unless it is positioned itself). And those answers checking $( document ).width() and .height() fall prey to jQuery's buggy detection of document size.
  • 它们不会以一种可靠的跨浏览器方式捕捉定位内容的效果。基于身体大小的答案完全忽略了这一点(除非身体本身被定位,否则它不是这些内容的偏移父元素)。并且这些答案检查$(document).width()和.height()是jQuery对文档大小的bug检测的结果。
  • Relying on window.innerWidth, if the browser supports it, makes your code fail to detect scroll bars in mobile browsers, where the width of the scroll bar is generally 0. They are just shown temporarily as an overlay and don't take up space in the document. Zooming on mobile also becomes a problem that way (long story).
  • 依靠窗口。如果浏览器支持innerWidth,则会使代码无法检测到移动浏览器中的滚动条,在移动浏览器中,滚动条的宽度通常为0。它们只是临时显示为一个覆盖层,不占用文档中的空间。移动移动也成为一个问题(长故事)。
  • The detection can be thrown off when people explicitly set the overflow of both the html and body element to non-default values (what happens then is a little involved - see this description).
  • 当人们显式地将html和body元素的溢出值设置为非默认值时(这时发生的情况有点复杂——请参阅本文的描述),可以取消检测。
  • In most answers, body padding, borders or margins are not detected and distort the results.
  • 在大多数答案中,没有检测到正文填充、边框或边距并扭曲结果。

I have spent more time than I would have imagined on a finding a solution that "just works" (cough). The algorithm I have come up with is now part of a plugin, jQuery.isInView, which exposes a .hasScrollbar method. Have a look at the source if you wish.

我花了比我想象中更多的时间去寻找一个“有效”的解决方案(咳嗽)。我想到的算法现在是jQuery插件的一部分。提供了一个. hasscrollbar方法。如果你愿意的话,可以看看它的出处。

In a scenario where you are in full control of the page and don't have to deal with unknown CSS, using a plugin may be overkill - after all, you know which edge cases apply, and which don't. However, if you need reliable results in an unknown environment, then I don't think the solutions outlined here will be enough. You are better off using a well-tested plugin - mine or anybody elses.

在一个你完全控制页面并且不需要处理未知CSS的场景中,使用一个插件可能有点过头了——毕竟,你知道哪些边情况适用,哪些不适用。然而,如果您需要在未知环境中得到可靠的结果,那么我认为这里列出的解决方案是不够的。你最好使用一个测试良好的插件——我的或者其他的。

#5


14  

This one did works for me:

这个方法对我确实有效:

function hasVerticalScroll(node){
    if(node == undefined){
        if(window.innerHeight){
            return document.body.offsetHeight> window.innerHeight;
        }
        else {
            return  document.documentElement.scrollHeight > 
                document.documentElement.offsetHeight ||
                document.body.scrollHeight>document.body.offsetHeight;
        }
    }
    else {
        return node.scrollHeight> node.offsetHeight;
    }
}

For the body, just use hasVerticalScroll().

对于主体,只需使用hasVerticalScroll()。

#6


9  

var hasScrollbar = window.innerWidth > document.documentElement.clientWidth;

#7


2  

I found vanila solution

我发现香草香精的解决方案

var hasScrollbar = function() {
  // The Modern solution
  if (typeof window.innerWidth === 'number')
    return window.innerWidth > document.documentElement.clientWidth

  // rootElem for quirksmode
  var rootElem = document.documentElement || document.body

  // Check overflow style property on body for fauxscrollbars
  var overflowStyle

  if (typeof rootElem.currentStyle !== 'undefined')
    overflowStyle = rootElem.currentStyle.overflow

  overflowStyle = overflowStyle || window.getComputedStyle(rootElem, '').overflow

    // Also need to check the Y axis overflow
  var overflowYStyle

  if (typeof rootElem.currentStyle !== 'undefined')
    overflowYStyle = rootElem.currentStyle.overflowY

  overflowYStyle = overflowYStyle || window.getComputedStyle(rootElem, '').overflowY

  var contentOverflows = rootElem.scrollHeight > rootElem.clientHeight
  var overflowShown    = /^(visible|auto)$/.test(overflowStyle) || /^(visible|auto)$/.test(overflowYStyle)
  var alwaysShowScroll = overflowStyle === 'scroll' || overflowYStyle === 'scroll'

  return (contentOverflows && overflowShown) || (alwaysShowScroll)
}

#8


2  

Oddly none of these solutions tell you if a page has a vertical scrollbar.

奇怪的是,这些解决方案都不能告诉您页面是否具有垂直滚动条。

window.innerWidth - document.body.clientWidth will give you the width of the scrollbar. This should work in anything IE9+ (not tested in the lesser browsers). (Or to strictly answer the question, !!(window.innerWidth - document.body.clientWidth)

窗口。innerWidth——document.body。clientWidth将为您提供滚动条的宽度。这应该适用于任何IE9+(未在较小的浏览器中测试)。或者严格地回答这个问题,!!innerWidth - document.body.clientWidth)

Why? Let's say you have a page where the content is taller than the window height and the user can scroll up/down. If you're using Chrome on a Mac with no mouse plugged in, the user will not see a scrollbar. Plug a mouse in and a scrollbar will appear. (Note this behaviour can be overridden, but that's the default AFAIK).

为什么?假设你有一个页面,内容比窗口高,用户可以向上/向下滚动。如果你在没有鼠标插入的Mac电脑上使用Chrome,用户将看不到滚动条。插入鼠标,滚动条就会出现。(注意这个行为可以被重写,但这是默认的AFAIK)。

#9


2  

    <script>
    var scrollHeight = document.body.scrollHeight;
    var clientHeight = document.documentElement.clientHeight;
    var hasVerticalScrollbar = scrollHeight > clientHeight;

    alert(scrollHeight + " and " + clientHeight); //for checking / debugging.
    alert("hasVerticalScrollbar is " + hasVerticalScrollbar + "."); //for checking / debugging.
    </script>

This one will tell you if you have a scrollbar or not. I've included some information that may help with debugging, which will display as a JavaScript alert.

这个会告诉你你是否有滚动条。我已经包含了一些可能有助于调试的信息,这些信息将作为JavaScript警报显示。

Put this in a script tag, after the closing body tag.

在结束主体标记之后,将其放入脚本标记中。

#10


0  

Other solutions didn't work in one of my projects and I've ending up checking overflow css property

其他解决方案在我的一个项目中不起作用,我最后检查了overflow css属性

function haveScrollbar() {
    var style = window.getComputedStyle(document.body);
    return style["overflow-y"] != "hidden";
}

but it will only work if scrollbar appear disappear by changing the prop it will not work if the content is equal or smaller than the window.

但是,只有当滚动条通过改变支柱出现消失时,它才会工作,如果内容等于或小于窗口,它就不会工作。

#11


0  

I wrote an updated version of Kees C. Bakker's answer:

我写了更新版的Kees C. Bakker的回答:

const hasVerticalScroll = (node) => {
  if (!node) {
    if (window.innerHeight) {
      return document.body.offsetHeight > window.innerHeight
    }
    return (document.documentElement.scrollHeight > document.documentElement.offsetHeight)
      || (document.body.scrollHeight > document.body.offsetHeight)
  }
  return node.scrollHeight > node.offsetHeight
}

if (hasVerticalScroll(document.querySelector('body'))) {
  this.props.handleDisableDownScrollerButton()
}

The function returns true or false depending whether the page has a vertical scrollbar or not.

函数返回true或false,这取决于页面是否具有垂直滚动条。

For example:

例如:

const hasVScroll = hasVerticalScroll(document.querySelector('body'))

if (hasVScroll) {
  console.log('HAS SCROLL', hasVScroll)
}