How can I check if a scrollbar is visible?

后端 未结 19 2607
情话喂你
情话喂你 2020-11-22 14:39

Is it possible to check the overflow:auto of a div?

For example:

HTML

19条回答
  •  名媛妹妹
    2020-11-22 15:32

    (scrollWidth/Height - clientWidth/Height) is a good indicator for the presence of a scrollbar, but it will give you a "false positive" answer on many occasions. if you need to be accurate i would suggest using the following function. instead of trying to guess if the element is scrollable - you can scroll it...

    function isScrollable( el ){
      var y1 = el.scrollTop;
      el.scrollTop  += 1;
      var y2 = el.scrollTop;
      el.scrollTop  -= 1;
      var y3 = el.scrollTop;
      el.scrollTop   = y1;
      var x1 = el.scrollLeft;
      el.scrollLeft += 1;
      var x2 = el.scrollLeft;
      el.scrollLeft -= 1;
      var x3 = el.scrollLeft;
      el.scrollLeft  = x1;
      return {
        horizontallyScrollable: x1 !== x2 || x2 !== x3,
        verticallyScrollable: y1 !== y2 || y2 !== y3
      }
    }
    function check( id ){
      alert( JSON.stringify( isScrollable( document.getElementById( id ))));
    }
    #outer1, #outer2, #outer3 {
      background-color: pink;
      overflow: auto;
      float: left;
    }
    #inner {
      width:  150px;
      height: 150px;
    }
    button {  margin: 2em 0 0 1em; }

提交回复
热议问题