如何使用香草javascript确定<div>是否可滚动?

时间:2019-11-21 13:50:17

标签: javascript html css scroll

此处(Detect if the DIV have scroll bar or not [duplicate])以及其他关于SO的问题均未正确回答该问题。

答案没有考虑到div的内容可能有一个float,之后没有清除。 div.clientHeightdiv.scrollHeight不能用于检测滚动行为。如以下示例所示:

window.addEventListener("load",function(){
  var div = document.querySelector(".container");
  document.querySelector(".clientHeight").innerHTML = div.clientHeight;
  document.querySelector(".scrollHeight").innerHTML = div.scrollHeight;
});
.container{
  width: 50px;
  min-height: 20px;
  border: 1px solid red;
}
.floated{
  float: left;
}
<table>
  <thead>
    <tr>
      <th>clientHeight</th>
      <th>scrollHeight</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td class="clientHeight"></td>
      <td class="scrollHeight"></td>
    </tr>
  </tbody>
</table>
<div class="container">
  <div class="floated">Lorem ipsum dolor sit amet blah blah blah blah blah</div>
</div>

Codepen

1 个答案:

答案 0 :(得分:0)

检查父容器是否具有overflow-yoverflow-x的{​​{1}},overflowauto

用于检查是否可水平滚动的javascript:

scroll