如何使用Javascript检测HTML iFrame中滚动条的存在?

26

我如何使用JavaScript检测HTML iFrame中滚动条的存在?

我已经尝试过:

        var vHeight = 0;
        if (document.all) {
          if (document.documentElement) {
            vHeight = document.documentElement.clientHeight;
          } else {
            vHeight = document.body.clientHeight
          }
    } else {
      vHeight = window.innerHeight;
    }

    if (document.body.offsetHeight > vHeight) {
      //when theres a scrollbar
    }else{
      //when theres not a scrollbar
    }

我也曾尝试过:

           this.scrollLeft=1;
    if (this.scrollLeft>0) {
        //when theres a scrollbar
        this.scrollLeft=0;
        }else{
        //when theres not a scrollbar
        return false;
    }

一直没有成功...

我在DOM检查器上搜索了JavaScript对象,但没找到什么内容。

是否可能在 JavaScript 中检测 iframe 中是否存在滚动条?


iframe 的内容来自同一域。

目前为止还没有成功。

alt文本 http://www.upvtp.com.br/file.php/1/help_key.jpg

6个回答

48
var root= document.compatMode=='BackCompat'? document.body : document.documentElement;
var isVerticalScrollbar= root.scrollHeight>root.clientHeight;
var isHorizontalScrollbar= root.scrollWidth>root.clientWidth;

这会检测是否需要滚动条。对于默认的iframe情况,这与是否有滚动条相同,但如果强制打开或关闭滚动条(在父文档中使用“scrolling =”yes“ / ”no“”属性,或CSS“overflow:scroll / hidden”在iframe文档中),则可能会有所不同。


1
这应该是答案。 - Julian
为什么您要测试“BackCompat”而不是在所有兼容模式下都使用documentElement - bab
1
@bab 当您处于 Quirks Mode(IE5 兼容模式)时,顶级文档滚动条位于 body 元素上而不是 html 上。 - bobince
为了更简化,您可以用 var root = document.scrollingElement; 替换 compatMode 检查。 - Robbendebiene

9

使用jQuery,您可以比较文档高度、滚动位置和视口高度,这可能会为您提供所需的答案。

大致如下:

$(window).scroll(function(){
  if(isMyStuffScrolling()){
    //There is a scroll bar here!
  }
}); 

function isMyStuffScrolling() {
  var docHeight = $(document).height();
  var scroll    = $(window).height() + $(window).scrollTop();
  return (docHeight == scroll);
} 

1
谢谢您的回答,但是您的代码只测试了当我尝试移动滚动条时的情况。我想在页面加载时进行测试。 - Bonfocchi
3
很抱歉,但是这不是一个正确的解决方案。 :( 你的代码实际上是检查文档是否滚动到底部。这里有一个证明:http://jsfiddle.net/vvdb0292/2/。我认为bobince的答案是正确的。 - kaboom

3
$(window).scroll(function(){
  if(isMyStuffScrolling()){
//scrolling
  }else{
//not scrolling
}
}); 

function isMyStuffScrolling() {
  var docHeight = $(document).height();
  var scroll    = $(window).height() ;//+ $(window).scrollTop();
  if(docHeight > scroll) return true;
  else return false;
}

这段代码是基于Jon的Winstanley代码改进而来的。


1

如果 iframe 的内容来自另一个域,由于 JavaScript 安全限制,我认为这是不可能完成的。

编辑: 在这种情况下,可以给 iframe 命名为 name='someframe' 和 id='someframe2',然后将 frames['someframe'].document.body.offsetWidth 与 document.getElementById('someframe2').offsetWidth 进行比较,以获得答案。


1
iframe的内容来自同一个域名。 - Bonfocchi

1

我发现这在任何元素上都有效,至少在Chrome浏览器上是如此:

hasVerticalScrollbar = (element.scrollHeight > element.offsetHeight)
        || 
(element.scrollHeight > element.clientHeight

水平滚动条可以通过使用 Width 而不是 Height 来检测。

0

我认为你的第二次尝试是正确的方向。除了使用this,你应该尝试滚动/检查document.body


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接