jQuery check if element is visible inside scrollable div

喜欢而已 提交于 2020-01-04 04:07:07

问题


Ok so I use the following code to check whether an element is visible on-screen.

(function($) {

/**
    * Copyright 2012, Digital Fusion
    * Licensed under the MIT license.
    * http://teamdf.com/jquery-plugins/license/
    *
    * @author Sam Sehnert
    * @desc A small plugin that checks whether elements are within
    *     the user visible viewport of a web browser.
    *     only accounts for vertical position, not horizontal.
 */

$.fn.visible = function(partial) {

    var $t            = $(this),
        $w            = $(window),
        viewTop       = $w.scrollTop(),
        viewBottom    = viewTop + $w.height(),
        _top          = $t.offset().top,
        _bottom       = _top + $t.height(),
        compareTop    = partial === true ? _bottom : _top,
        compareBottom = partial === true ? _top : _bottom;

  return ((compareBottom <= viewBottom) && (compareTop >= viewTop));

};

})(jQuery);

However, I would like to use this piece of code so that it checks whether it is visible inside a scrollable element. Specifically the main tag which I used for my main content. How would I go about changing this code so that it works for my scrollable element? I'm not quite sure what to do. I've already tried changing $w variable to $('main') but that seems to behave odd.


回答1:


However, I would like to use this piece of code so that it checks whether it is visible inside a scrollable element.

The plugin is limited to detecting whatever is a direct child of body. That pretty much makes any nested element undetectable to the plugin. See this explanation.



来源:https://stackoverflow.com/questions/34843489/jquery-check-if-element-is-visible-inside-scrollable-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!