How can I check if a scrollbar is visible?

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

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

For example:

HTML

19条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 15:38

    A No Framework JavaScript Approach, checks for both vertical and horizontal

     /*
     * hasScrollBars
     * 
     * Checks to see if an element has scrollbars
     * 
     * @returns {object}
     */
    Element.prototype.hasScrollBars = function() {
        return {"vertical": this.scrollHeight > this.style.height, "horizontal": this.scrollWidth > this.style.width};
    }
    

    Use it like this

    if(document.getElementsByTagName("body")[0].hasScrollBars().vertical){
                alert("vertical");
    }
    
            if(document.getElementsByTagName("body")[0].hasScrollBars().horizontal){
                alert("horizontal");
    }
    

提交回复
热议问题