jQuery检查元素在可滚动div中是否可见 [英] jQuery check if element is visible inside scrollable div

查看:109
本文介绍了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.

这篇关于jQuery检查元素在可滚动div中是否可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆