簡體   English   中英

檢測頁面是否有垂直滾動條?

[英]Detect if a page has a vertical scrollbar?

我只想要一些簡單的 JQ/JS 來檢查當前頁面/窗口(不是特定元素)是否有垂直滾動條。

谷歌搜索給我的東西對於這個基本功能來說似乎過於復雜。

如何才能做到這一點?

$(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:<");
    }
});

嘗試這個:

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

但是,這只會告訴您垂直 scrollHeight 是否大於可查看內容的高度。 hasVScroll變量將包含 true 或 false。

如果您需要進行更徹底的檢查,請將以下內容添加到上面的代碼中:

// 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");

我嘗試了以前的答案,但似乎沒有起作用 $("body").height() 不一定代表整個 html 高度。

我已更正解決方案如下:

// 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:<"); 
} 

讓我們把這個問題從死里復活 ;) 谷歌沒有給你一個簡單的解決方案是有原因的。 特殊情況和瀏覽器怪癖會影響計算,並沒有看起來那么簡單。

不幸的是,到目前為止,這里列出的解決方案存在問題。 我根本沒有貶低它們的意思——它們是很好的起點,並且觸及了更強大的方法所需的所有關鍵屬性。 但我不建議從任何其他答案中復制和粘貼代碼,因為

  • 它們不會以可靠的跨瀏覽器的方式捕捉定位內容的效果。 基於正文大小的答案完全忽略了這一點(正文不是此類內容的偏移父級,除非它本身被定位)。 而那些檢查$( document ).width().height()答案會成為jQuery 對文檔大小的錯誤檢測的犧牲品。
  • 依賴window.innerWidth ,如果瀏覽器支持,會讓你的代碼在手機瀏覽器中檢測不到滾動條,滾動條的寬度一般為0,只是暫時顯示為疊加,不占空間在文件中。 在移動設備上縮放也成為一個問題(長話短說)。
  • 當人們將htmlbody元素的溢出顯式設置為非默認值時,檢測可能會被取消(然后發生的事情有點復雜 - 請參閱此描述)。
  • 在大多數答案中,沒有檢測到正文填充、邊框或邊距,並且會扭曲結果。

我花了比我想象的更多的時間來尋找“有效”的解決方案(咳嗽)。 我提出的算法現在是插件jQuery.isInView 的一部分,它公開了一個.hasScrollbar方法 如果您願意,請查看

在您完全控制頁面並且不必處理未知 CSS 的情況下,使用插件可能有點矯枉過正——畢竟,您知道哪些邊緣情況適用,哪些不適用。 但是,如果您需要在未知環境中獲得可靠的結果,那么我認為這里列出的解決方案還不夠。 您最好使用經過良好測試的插件 - 我的或其他任何人。

這個對我有用:

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

對於正文,只需使用hasVerticalScroll()

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

奇怪的是,這些解決方案都沒有告訴您頁面是否具有垂直滾動條。

window.innerWidth - document.body.clientWidth會給你滾動條的寬度。 這應該適用於任何 IE9+(未在較小的瀏覽器中測試)。 (或者嚴格回答這個問題, !!(window.innerWidth - document.body.clientWidth)

為什么? 假設您有一個頁面,其中內容高於窗口高度,並且用戶可以向上/向下滾動。 如果您在未插入鼠標的 Mac 上使用 Chrome,用戶將看不到滾動條。 插入鼠標,會出現一個滾動條。 (請注意,此行為可以被覆蓋,但這是默認的 AFAIK)。

    <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>

這將告訴您是否有滾動條。 我已經包含了一些可能有助於調試的信息,這些信息將顯示為 JavaScript 警報。

把它放在一個 script 標簽中,在結束 body 標簽之后。

我找到了香草解決方案

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

我用

function windowHasScroll()
{
    return document.body.clientHeight > document.documentElement.clientHeight;
}

只需將文檔根元素(即 html 元素)的寬度與窗口的內部部分進行比較:

if ((window.innerWidth - document.documentElement.clientWidth) >0) console.log('V-scrollbar active')

如果您還需要知道滾動條寬度:

vScrollbarWidth = window.innerWidth - document.documentElement.clientWidth;

其他解決方案在我的一個項目中不起作用,我最終檢查了溢出的 css 屬性

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

但它只會在滾動條出現時通過更改道具消失,如果內容等於或小於窗口,它將不起作用。

我寫了 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()
}

該函數根據頁面是否具有垂直滾動條返回 true 或 false。

例如:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM