微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 获取不可见的内部div

我有一个div(parentDivStyle),其位置绝对是我的父div.然后我在父div中有5个子(childDivStyle)div,位置相对.我已将溢出设置为隐藏的父div.因此,一些儿童div不可见.我想得到 jquery看不到的div.有什么办法吗?

我用google搜索了大部分与“可见”属性相关的结果,这不是我想要的.而且我也不喜欢任何插件.请帮忙.

CSS

.parentDivStyle {
    overflow:hidden;
    width:300px;
    height:50px;
    position:absolute;
    background:#ccc;
    float:left;
}
.childDivStyle {
    width:100px;
    height:50px;
    position:relative;
    float:left;
    background:red;
    border: 1px solid black;
}

HTML

<div class="parentDivStyle">
<div class="childDivStyle">1</div>
<div class="childDivStyle">2</div>
<div class="childDivStyle">3</div>
<div class="childDivStyle">4</div>
<div class="childDivStyle">5</div>
</div>

JSFIDDLE

解决方法

使用 this answer获取元素的坐标,可以找出元素相对于彼此的位置.一旦知道可见区域的坐标,就可以轻松找出可见的子元素.

这将告诉您元素是否可见,如果不可见,它们是否与容器相关.

displayCoords = function(element) {
    var rect = element.getBoundingClientRect();
    console.log(rect.top,rect.right,rect.bottom,rect.left);   

    var childElements = element.children;
    for(i = 0; i < childElements.length; i++)
    {
        childRect = childElements[i].getBoundingClientRect();
        console.log(childRect.top,childRect.right,childRect.bottom,childRect.left);  
        if(childRect.top >=  rect.bottom)
            console.log("not visible -- off the bottom of element");
        else if(childRect.left >= rect.right)
            console.log("not visible -- off the right of element");
        else if(childRect.bottom <= rect.top)
            console.log("not visible -- off the top of element");
        else if(childRect.right <= rect.left)
            console.log("not visible -- off the left of element");
    }

}

我分叉你的JSfiddle here

原文地址:https://www.jb51.cc/js/156739.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐