最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Scrollbar appeardisappear event in jQuery? - Stack Overflow

programmeradmin6浏览0评论

Is there a simple way in jQuery to detect when scrollbars appear and disappear on a div that has overflow:auto? (Like an event? Fingers crossed...)

(I'd prefer not to have to look at the height of the content of the div)

Is there a simple way in jQuery to detect when scrollbars appear and disappear on a div that has overflow:auto? (Like an event? Fingers crossed...)

(I'd prefer not to have to look at the height of the content of the div)

Share Improve this question edited Apr 11, 2020 at 16:31 Brian Tompsett - 汤莱恩 5,88372 gold badges61 silver badges133 bronze badges asked Apr 5, 2010 at 11:18 TravisTravis 2,0214 gold badges22 silver badges31 bronze badges 2
  • Have a look at OrganicPanda's solution on this other thread: http://stackoverflow.com/questions/2175992/detect-when-window-vertical-scrollbar-appears – Jean-François Beauchamp Commented Mar 7, 2017 at 17:18
  • Possible duplicate of Detect when window vertical scrollbar appears – user Commented Apr 16, 2017 at 10:12
Add a comment  | 

3 Answers 3

Reset to default 7

Another way to achieve this is to check whether there are scrollbars present using scrollLeft or scrollTop:

//nudge the scrollbar away from its starting position

$('#your_selector').scrollLeft(1);

//A value of 0 is assigned if the scrollbars are at their default position, 
//or are abscent

if($('#your_selector').scrollLeft() !== 0) return true;

//put the scrollbar back to its starting position

$('#your_selector').scrollLeft(0);

As others have said, there is no easy way. Here's some code I've used in the past to detect if a scrollbar is present.

// Used like $('#my-id').hasScrollbar();

jQuery.fn.hasScrollbar = function() {
    var scrollHeight = this.get(0).scrollHeight;

    //safari's scrollHeight includes padding
    if ($.browser.safari)
        scrollHeight -= parseInt(this.css('padding-top')) + parseInt(this.css('padding-bottom'));

    if (this.height() < scrollHeight)
        return true;
    else
        return false;
}

You'll manually need to call this after adding or removing content from the div and it probably will only work if you call it on visible elements, but it's better than starting from scratch.

As far as I know, there is not event for that.
However, you "could" write your own special event for that, I guess you have to check for the height and width.

It should be possible to detect scrollbars if the .innerHeight exceds the .outerHeight value of an element.

发布评论

评论列表(0)

  1. 暂无评论