检测<div>何时显示



我的代码中有4个<div>。我使用JavaScript来显示和隐藏它们。现在管理起来越来越困难,因此我需要检测特定的<div>是否显示或隐藏。我不确定如何做到这一点,用哪种方式编码?JQuery或Jqtouch可能很好。感谢

如果您可以使用jQuery来帮助您,您可以使用:

$( "yourDivSelector" ).is( ":visible" );

没有jQuery,你可以做:

alert( isVisible( "divOne" ) );
alert( isVisible( "divTwo" ) );
alert( isVisible( "divThree" ) );
function isVisible( elementId ) {
    var element = document.getElementById( elementId );
    return window.getComputedStyle( element, null ).display != "none";
}

jsFiddle:http://jsfiddle.net/davidbuzatto/N3wf6/

有关window.getComputedStyle的详细信息,请点击此处:https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle

这个函数似乎可以随心所欲。它检查不显示和隐藏可见性。

JavaScript函数检查DOM元素的可见性

function isVisible(obj)
{
    if (obj == document) return true
    if (!obj) return false
    if (!obj.parentNode) return false
    if (obj.style) {
        if (obj.style.display == 'none') return false
        if (obj.style.visibility == 'hidden') return false
    }
    //Try the computed style in a standard way
    if (window.getComputedStyle) {
        var style = window.getComputedStyle(obj, "")
        if (style.display == 'none') return false
        if (style.visibility == 'hidden') return false
    }
    //Or get the computed style using IE's silly proprietary way
    var style = obj.currentStyle
    if (style) {
        if (style['display'] == 'none') return false
        if (style['visibility'] == 'hidden') return false
    }
    return isVisible(obj.parentNode)
}

示例用法

if (isVisible(document.getElementById("myelement"))) {
    // Element is visible.
}

演示

因为我不能100%确定你在做什么隐藏/显示。。。

但是如果你设置了一个属性,例如显示

那么。。

function elementhidden()
{
    1. Get your element
    2. Check the elemnet atrribute status
    3. If its hide value then return true
    4. If its show value then return false
}

提供一个你做什么的例子,这样我就可以制作代码了。。

您可以使用document.elementFromPoint(x,y)将div的位置作为x和y传递,并检查它是否是好对象。

这假设没有其他元素覆盖您的div的左上角。

这可能取决于你所说的"可见":"完全可见"?"至少有一点可见"?视口中由于滚动位置而不可见的部分怎么办?如果浏览器窗口部分位于屏幕之外(这可能很棘手)?

取决于div的隐藏方式,但您可能会使用

if(document.getElementById("myDiv").style.display=="none"){
    //do something
}

最新更新