javascript:无法准确获得滚动条高度

时间:2016-01-03 21:38:41

标签: javascript html document

我试图获得滚动条高度,经过一段时间我发现了一个想法来获得高度:

CSS:

#content {
    font-size: 18px;
    line-height: 90px;
    overflow: hidden;
}

#bt {
    background-color: #fff;
    width: 10px;
    outline: 1px solid red;
    position: fixed;
}

HTML:

 <button type="button" onclick="barHeight()">Press it</button>

 <div id="bt"></div>

 <div id="content">
  Lorem Ipsum is simply dummy tex.................
 </div>

JS:

function barHeight() {
 var scrHeight = window.innerHeight; // supposed to be 799 px
 var contentBox = document.getElementById("content");
 var contentHeight = contentBox.scrollHeight; //
 var targetHeight = ( ( scrHeight / contentHeight ) * 100 );
 var testBox = document.getElementById("bt");

 if(scrHeight < contentHeight) {
    testBox.style.height = targetHeight + "%";
 } else if( scrHeight > contentHeight ) {
    testBox.innerHTML = "0px";
 }


}

但是当我测量它时,它的高度并不像实际的滚动条那样。

提前致谢!

编辑: How can I get the browser's scrollbar sizes?该链接中的解决方案对我不起作用,至少我的脚本可以很容易地运行,它对我有用但不准确,

1 个答案:

答案 0 :(得分:0)

这是另一种方式。

isScrollable (...)函数检查content div是否溢出并且可以滚动(带有overflow: hidden的元素仍然可滚动,但其滚动条被隐藏)。

getScrollBarSize (...)获取垂直滚动条的宽度(水平滚动条具有相同的高度)。

function barHeight() {    
 if(isScrollable(document.getElementById("content"))) {
    document.getElementById("bt").innerHTML = getScrollBarSize() + "px";
 } else {
    document.getElementById("bt").innerHTML = "0px";
 }
}

function getScrollBarSize () {
  var el = document.createElement("div");
  el.setAttribute("style", "width:80px;height:80px;overflow:scroll;position: absolute;visibility:hidden;");
  document.body.appendChild(el);
  var elw = el.offsetWidth - el.clientWidth;
  document.body.removeChild(el);
  return (elw);
  
}
function isScrollable (el) {
  return el.scrollHeight > el.clientHeight;  
};
button {
  position: absolute;
  top: 5px;
  left: 300px;
}
#content {
    font-size: 8px;
    line-height: 30px;
    overflow: auto;
    height: 200px;
    width: 200px;
    border: 1px solid black;
}

#bt {
    background-color: #9f9;
    width: 100px;
    outline: 1px solid red;
    position: fixed;
}
<button type="button" onclick="barHeight()">Press it</button>

 <div id="bt"></div>

 <div id="content">
  Lorem Ipsum is simply dummy tex.................<br>
  Lorem Ipsum is simply dummy tex.................<br>
  Lorem Ipsum is simply dummy tex.................<br>
  Lorem Ipsum is simply dummy tex.................<br>
  Lorem Ipsum is simply dummy tex.................<br>
  Lorem Ipsum is simply dummy tex.................<br>
  Lorem Ipsum is simply dummy tex.................<br>
  Lorem Ipsum is simply dummy tex.................<br>
  Lorem Ipsum is simply dummy tex.................<br>
 </div>