jQuery检查元素在可滚动div中是否可见
好的,所以我使用以下代码检查元素是否在屏幕上可见。
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);
但是,我想使用这段代码,以便检查它是否在可滚动元素。特别是我用于主要内容的主要标签。我将如何更改此代码以使其适用于我的可滚动元素?
我不太清楚该怎么做。我已经尝试将$ w变量更改为$('main'),但这似乎表现得很奇怪。
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.
但是,我想使用这段代码,以便检查它是否在可滚动元素中可见。
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.