505

有什么方法可以检查一个元素在纯 JS(没有 jQuery)中是否可见?

因此,例如,在此页面:Performance Bikes中,如果您将鼠标悬停在“交易”上(在顶部菜单上),则会出现一个交易窗口,但一开始并未显示。它在 HTML 中,但不可见。

那么,给定一个 DOM 元素,我如何检查它是否可见?我试过了:

window.getComputedStyle(my_element)['display']);

但它似乎没有工作。我想知道我应该检查哪些属性。我想到了:

display !== 'none'
visibility !== 'hidden'

还有其他我可能会想念的吗?

4

22 回答 22

814

根据这个 MDN 文档,只要元素或其任何父元素通过显示样式属性隐藏,元素的offsetParent属性就会返回。null只要确保元素没有固定。如果页面上没有position: fixed;元素,则检查此内容的脚本可能如下所示:

// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    return (el.offsetParent === null)
}

另一方面,如果您确实有可能在此搜索中被捕获的位置固定元素,那么您将遗憾地(并且慢慢地)必须使用window.getComputedStyle(). 这种情况下的功能可能是:

// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    var style = window.getComputedStyle(el);
    return (style.display === 'none')
}

选项 #2 可能更简单一些,因为它考虑了更多的边缘情况,但我敢打赌它也会慢很多,所以如果你必须多次重复这个操作,最好避免它。

于 2014-02-11T08:23:09.347 回答
134

对于我来说,所有其他解决方案都因某种情况而崩溃..

请参阅以下位置的获胜答案:

http://plnkr.co/edit/6CSCA2fe4Gqt4jCBP2wu?p=preview

最终,我决定最好的解决方案是$(elem).is(':visible')- 然而,这不是纯 JavaScript。这是jquery ..

所以我偷看了他们的来源,找到了我想要的

jQuery.expr.filters.visible = function( elem ) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

这是来源:https ://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js

于 2015-10-31T20:49:05.310 回答
85

如果您对用户可见的感兴趣:

function isVisible(elem) {
    if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
    const style = getComputedStyle(elem);
    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if (style.opacity < 0.1) return false;
    if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0) {
        return false;
    }
    const elemCenter   = {
        x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
        y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
    };
    if (elemCenter.x < 0) return false;
    if (elemCenter.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
    if (elemCenter.y < 0) return false;
    if (elemCenter.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
    let pointContainer = document.elementFromPoint(elemCenter.x, elemCenter.y);
    do {
        if (pointContainer === elem) return true;
    } while (pointContainer = pointContainer.parentNode);
    return false;
}

测试(使用mocha术语):

describe.only('visibility', function () {
    let div, visible, notVisible, inViewport, leftOfViewport, rightOfViewport, aboveViewport,
        belowViewport, notDisplayed, zeroOpacity, zIndex1, zIndex2;
    before(() => {
        div = document.createElement('div');
        document.querySelector('body').appendChild(div);
        div.appendChild(visible = document.createElement('div'));
        visible.style       = 'border: 1px solid black; margin: 5px; display: inline-block;';
        visible.textContent = 'visible';
        div.appendChild(inViewport = visible.cloneNode(false));
        inViewport.textContent = 'inViewport';
        div.appendChild(notDisplayed = visible.cloneNode(false));
        notDisplayed.style.display = 'none';
        notDisplayed.textContent   = 'notDisplayed';
        div.appendChild(notVisible = visible.cloneNode(false));
        notVisible.style.visibility = 'hidden';
        notVisible.textContent      = 'notVisible';
        div.appendChild(leftOfViewport = visible.cloneNode(false));
        leftOfViewport.style.position = 'absolute';
        leftOfViewport.style.right = '100000px';
        leftOfViewport.textContent = 'leftOfViewport';
        div.appendChild(rightOfViewport = leftOfViewport.cloneNode(false));
        rightOfViewport.style.right       = '0';
        rightOfViewport.style.left       = '100000px';
        rightOfViewport.textContent = 'rightOfViewport';
        div.appendChild(aboveViewport = leftOfViewport.cloneNode(false));
        aboveViewport.style.right       = '0';
        aboveViewport.style.bottom       = '100000px';
        aboveViewport.textContent = 'aboveViewport';
        div.appendChild(belowViewport = leftOfViewport.cloneNode(false));
        belowViewport.style.right       = '0';
        belowViewport.style.top       = '100000px';
        belowViewport.textContent = 'belowViewport';
        div.appendChild(zeroOpacity = visible.cloneNode(false));
        zeroOpacity.textContent   = 'zeroOpacity';
        zeroOpacity.style.opacity = '0';
        div.appendChild(zIndex1 = visible.cloneNode(false));
        zIndex1.textContent = 'zIndex1';
        zIndex1.style.position = 'absolute';
        zIndex1.style.left = zIndex1.style.top = zIndex1.style.width = zIndex1.style.height = '100px';
        zIndex1.style.zIndex = '1';
        div.appendChild(zIndex2 = zIndex1.cloneNode(false));
        zIndex2.textContent = 'zIndex2';
        zIndex2.style.left = zIndex2.style.top = '90px';
        zIndex2.style.width = zIndex2.style.height = '120px';
        zIndex2.style.backgroundColor = 'red';
        zIndex2.style.zIndex = '2';
    });
    after(() => {
        div.parentNode.removeChild(div);
    });
    it('isVisible = true', () => {
        expect(isVisible(div)).to.be.true;
        expect(isVisible(visible)).to.be.true;
        expect(isVisible(inViewport)).to.be.true;
        expect(isVisible(zIndex2)).to.be.true;
    });
    it('isVisible = false', () => {
        expect(isVisible(notDisplayed)).to.be.false;
        expect(isVisible(notVisible)).to.be.false;
        expect(isVisible(document.createElement('div'))).to.be.false;
        expect(isVisible(zIndex1)).to.be.false;
        expect(isVisible(zeroOpacity)).to.be.false;
        expect(isVisible(leftOfViewport)).to.be.false;
        expect(isVisible(rightOfViewport)).to.be.false;
        expect(isVisible(aboveViewport)).to.be.false;
        expect(isVisible(belowViewport)).to.be.false;
    });
});
于 2017-01-17T13:36:37.330 回答
43

使用与 jQuery 相同的代码:

jQuery.expr.pseudos.visible = function( elem ) {
    return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length );
};

所以,在一个函数中:

function isVisible(e) {
    return !!( e.offsetWidth || e.offsetHeight || e.getClientRects().length );
}

在我的 Win/IE10、Linux/Firefox.45、Linux/Chrome.52...

非常感谢没有 jQuery 的 jQuery!

于 2016-08-10T12:43:06.847 回答
39

这可能会有所帮助: 通过将元素定位在最左边的位置来隐藏元素,然后检查 offsetLeft 属性。如果你想使用 jQuery,你可以简单地检查:visible选择器并获取元素的可见性状态。

HTML:

<div id="myDiv">Hello</div>

CSS:

<!-- for javaScript-->
#myDiv{
   position:absolute;
   left : -2000px;
}

<!-- for jQuery -->
#myDiv{
    visibility:hidden;
}

脚本:

var myStyle = document.getElementById("myDiv").offsetLeft;

if(myStyle < 0){
     alert("Div is hidden!!");
}

jQuery :

if(  $("#MyElement").is(":visible") == true )
{  
     alert("Div is visible!!");        
}

jsFiddle

于 2013-10-29T21:53:30.947 回答
30

接受的答案对我不起作用。

2020年细分。

  1. (elem.offsetParent !== null)方法在 Firefox 中运行良好,但在 Chrome 中运行良好。在 Chrome中,即使元素在页面中可见,position: fixed也会offsetParent返回。null

    用户 Phrogz 对具有不同属性的元素进行了大型测试(2,304 个 div)来证明该问题。https://stackoverflow.com/a/11639664/4481831使用多个浏览器运行它以查看差异。

    演示:

    //different results in Chrome and Firefox
    console.log(document.querySelector('#hidden1').offsetParent); //null Chrome & Firefox
    console.log(document.querySelector('#fixed1').offsetParent); //null in Chrome, not null in Firefox
        <div id="hidden1" style="display:none;"></div>
        <div id="fixed1" style="position:fixed;"></div>

  2. (getComputedStyle(elem).display !== 'none')不起作用,因为元素可能是不可见的,因为父显示属性之一设置为无,不会getComputedStyle捕捉到这一点。

    演示:

    var child1 = document.querySelector('#child1');
    console.log(getComputedStyle(child1).display);
    //child will show "block" instead of "none"
    <div id="parent1" style="display:none;">
      <div id="child1" style="display:block"></div>
    </div>

  3. (elem.clientHeight !== 0)。_ 此方法不受影响,position: fixed它还检查元素父级是否不可见。但是它对于没有 CSS 布局的简单元素有问题,请在此处查看更多信息

    演示:

    console.log(document.querySelector('#div1').clientHeight); //not zero
    console.log(document.querySelector('#span1').clientHeight); //zero
    <div id="div1">test1 div</div>
    <span id="span1">test2 span</span>

  4. (elem.getClientRects().length !== 0)似乎可以解决前 3 种方法的问题。但是,使用 CSS 技巧(除 之外display: none)隐藏在页面中的元素存在问题。

    演示

    console.log(document.querySelector('#notvisible1').getClientRects().length);
    console.log(document.querySelector('#notvisible1').clientHeight);
    console.log(document.querySelector('#notvisible2').getClientRects().length);
    console.log(document.querySelector('#notvisible2').clientHeight);
    console.log(document.querySelector('#notvisible3').getClientRects().length);
    console.log(document.querySelector('#notvisible3').clientHeight);
    <div id="notvisible1" style="height:0; overflow:hidden; background-color:red;">not visible 1</div>
    
    <div id="notvisible2" style="visibility:hidden; background-color:yellow;">not visible 2</div>
    
    <div id="notvisible3" style="opacity:0; background-color:blue;">not visible 3</div>

结论。

所以我向你展示的是,没有一种方法是完美的。要进行正确的可见性检查,您必须结合使用最后 3 种方法。

于 2019-11-28T22:47:09.410 回答
21

结合上面的几个答案:

function isVisible (ele) {
    var style = window.getComputedStyle(ele);
    return  style.width !== "0" &&
    style.height !== "0" &&
    style.opacity !== "0" &&
    style.display!=='none' &&
    style.visibility!== 'hidden';
}

就像 AlexZ 说的那样,如果您更具体地知道您在寻找什么,这可能会比您的其他一些选项慢,但这应该可以捕捉到隐藏元素的所有主要方式。

但是,这也取决于对您来说什么是可见的。例如,可以将 div 的高度设置为 0px,但内容仍然可见,具体取决于溢出属性。或者,可以将 div 的内容设置为与背景相同的颜色,以便用户看不到它,但仍会在页面上呈现。或者一个 div 可以移出屏幕或隐藏在其他 div 后面,或者它的内容可能不可见但边框仍然可见。在某种程度上,“可见”是一个主观术语。

于 2015-07-09T14:25:01.113 回答
9

与AlexZ 的 getComputedStyle() 解决方案相比,我有一个性能更高的解决方案,当一个人具有位置“固定”元素时,如果有人愿意忽略一些边缘情况(查看评论):

function isVisible(el) {
    /* offsetParent would be null if display 'none' is set.
       However Chrome, IE and MS Edge returns offsetParent as null for elements
       with CSS position 'fixed'. So check whether the dimensions are zero.

       This check would be inaccurate if position is 'fixed' AND dimensions were
       intentionally set to zero. But..it is good enough for most cases.*/
    if (!el.offsetParent && el.offsetWidth === 0 && el.offsetHeight === 0) {
        return false;
    }
    return true;
}

旁注:严格来说,“可见性”需要先定义。就我而言,我正在考虑一个可见的元素,只要我可以在其上运行所有 DOM 方法/属性而不会出现问题(即使不透明度为 0 或 CSS 可见性属性为“隐藏”等)。

于 2016-03-28T17:30:18.867 回答
7

如果元素是常规可见的(显示:块和可见性:可见),但某些父容器是隐藏的,那么我们可以使用clientWidthclientHeight进行检查。

function isVisible (ele) {
  return  ele.clientWidth !== 0 &&
    ele.clientHeight !== 0 &&
    (ele.style.opacity !== '' ? parseFloat(ele.style.opacity) > 0 : true);
}

Plunker(点击这里)

于 2015-03-09T00:41:10.347 回答
6

ohad navon 的回答有一点补充。

如果元素的中心属于另一个元素,我们将找不到它。

所以要确保元素的一个点被发现是可见的

function isElementVisible(elem) {
    if (!(elem instanceof Element)) throw Error('DomUtil: elem is not an element.');
    const style = getComputedStyle(elem);
    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if (style.opacity === 0) return false;
    if (elem.offsetWidth + elem.offsetHeight + elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0) {
        return false;
    }
    var elementPoints = {
        'center': {
            x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
            y: elem.getBoundingClientRect().top + elem.offsetHeight / 2
        },
        'top-left': {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().top
        },
        'top-right': {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().top
        },
        'bottom-left': {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().bottom
        },
        'bottom-right': {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().bottom
        }
    }

    for(index in elementPoints) {
        var point = elementPoints[index];
        if (point.x < 0) return false;
        if (point.x > (document.documentElement.clientWidth || window.innerWidth)) return false;
        if (point.y < 0) return false;
        if (point.y > (document.documentElement.clientHeight || window.innerHeight)) return false;
        let pointContainer = document.elementFromPoint(point.x, point.y);
        if (pointContainer !== null) {
            do {
                if (pointContainer === elem) return true;
            } while (pointContainer = pointContainer.parentNode);
        }
    }
    return false;
}
于 2017-12-05T06:29:38.213 回答
6

所以我发现是最可行的方法:

function visible(elm) {
  if(!elm.offsetHeight && !elm.offsetWidth) { return false; }
  if(getComputedStyle(elm).visibility === 'hidden') { return false; }
  return true;
}

这是基于以下事实:

  • 一个display: none元素(甚至是嵌套元素)没有宽度和高度。
  • visiblity甚至适用hidden于嵌套元素。

因此无需offsetParent在 DOM 树中进行测试或循环来测试哪个父级拥有visibility: hidden. 这即使在 IE 9 中也应该有效。

您可能会争论opacity: 0折叠的元素(有宽度但没有高度 - 反之亦然)是否也不是真正可见的。但话又说回来,他们并不是每个人都说隐藏的。

于 2016-04-20T08:19:52.407 回答
4

If we're just collecting basic ways of detecting visibility, let me not forget:

opacity > 0.01; // probably more like .1 to actually be visible, but YMMV

And as to how to obtain attributes:

element.getAttribute(attributename);

So, in your example:

document.getElementById('snDealsPanel').getAttribute('visibility');

But wha? It doesn't work here. Look closer and you'll find that visibility is being updated not as an attribute on the element, but using the style property. This is one of many problems with trying to do what you're doing. Among others: you can't guarantee that there's actually something to see in an element, just because its visibility, display, and opacity all have the correct values. It still might lack content, or it might lack a height and width. Another object might obscure it. For more detail, a quick Google search reveals this, and even includes a library to try solving the problem. (YMMV)

Check out the following, which are possible duplicates of this question, with excellent answers, including some insight from the mighty John Resig. However, your specific use-case is slightly different from the standard one, so I'll refrain from flagging:

(EDIT: OP SAYS HE'S SCRAPING PAGES, NOT CREATING THEM, SO BELOW ISN'T APPLICABLE) A better option? Bind the visibility of elements to model properties and always make visibility contingent on that model, much as Angular does with ng-show. You can do that using any tool you want: Angular, plain JS, whatever. Better still, you can change the DOM implementation over time, but you'll always be able to read state from the model, instead of the DOM. Reading your truth from the DOM is Bad. And slow. Much better to check the model, and trust in your implementation to ensure that the DOM state reflects the model. (And use automated testing to confirm that assumption.)

于 2013-10-29T22:04:49.053 回答
4

仅供参考,应注意getBoundingClientRect()在某些情况下可以工作。

例如,使用隐藏元素的简单检查display: none可能看起来像这样:

var box = element.getBoundingClientRect();
var visible = box.width && box.height;

这也很方便,因为它还涵盖了零宽度、零高度和position: fixed案例。但是,它不应报告用opacity: 0or隐藏的元素visibility: hidden(但也不会offsetParent)。

于 2015-07-01T18:39:14.857 回答
4

2021解决方案

根据MSD 文档,交互观察者异步观察目标元素与祖先元素或顶级文档视口的交集的变化。这意味着每次元素与视口相交时,交互观察者都会触发。

截至2021年,目前所有浏览器都支持交互观察器,除了IE。

执行

const el = document.getElementById("your-target-element");
const observer = new IntersectionObserver((entries) => {
    if(entries[0].isIntersecting){
         // el is visible
    } else {
         // el is not visible
    }
});
observer.observe(el);
于 2021-08-28T04:40:28.937 回答
4

改进@Guy Messika上面的答案,如果中心点 X < 0,则中断并返回 false 是错误的,因为右侧的元素可能会进入视图。这是一个修复:

private isVisible(elem) {
    const style = getComputedStyle(elem);

    if (style.display === 'none') return false;
    if (style.visibility !== 'visible') return false;
    if ((style.opacity as any) === 0) return false;

    if (
        elem.offsetWidth +
        elem.offsetHeight +
        elem.getBoundingClientRect().height +
        elem.getBoundingClientRect().width === 0
    ) return false;

    const elementPoints = {
        center: {
            x: elem.getBoundingClientRect().left + elem.offsetWidth / 2,
            y: elem.getBoundingClientRect().top + elem.offsetHeight / 2,
        },
        topLeft: {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().top,
        },
        topRight: {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().top,
        },
        bottomLeft: {
            x: elem.getBoundingClientRect().left,
            y: elem.getBoundingClientRect().bottom,
        },
        bottomRight: {
            x: elem.getBoundingClientRect().right,
            y: elem.getBoundingClientRect().bottom,
        },
    };

    const docWidth = document.documentElement.clientWidth || window.innerWidth;
    const docHeight = document.documentElement.clientHeight || window.innerHeight;

    if (elementPoints.topLeft.x > docWidth) return false;
    if (elementPoints.topLeft.y > docHeight) return false;
    if (elementPoints.bottomRight.x < 0) return false;
    if (elementPoints.bottomRight.y < 0) return false;

    for (let index in elementPoints) {
        const point = elementPoints[index];
        let pointContainer = document.elementFromPoint(point.x, point.y);
        if (pointContainer !== null) {
            do {
                if (pointContainer === elem) return true;
            } while (pointContainer = pointContainer.parentNode);
        }
    }
    return false;
}
于 2019-01-14T20:16:25.503 回答
2

来自http://code.jquery.com/jquery-1.11.1.js的 jQuery 代码有一个 isHidden 参数

var isHidden = function( elem, el ) {
    // isHidden might be called from jQuery#filter function;
    // in that case, element will be second argument
    elem = el || elem;
    return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};

所以看起来有一个与所有者文档相关的额外检查

我想知道这是否真的适用于以下情况:

  1. 基于 zIndex 隐藏在其他元素后面的元素
  2. 具有完全透明度的元素使它们不可见
  3. 位于屏幕外的元素(即左侧:-1000px)
  4. 具有可见性的元素:隐藏
  5. 显示元素:无
  6. 没有可见文本或子元素的元素
  7. 高度或宽度设置为 0 的元素
于 2014-11-13T18:02:25.027 回答
2
let element = document.getElementById('element');
let rect = element.getBoundingClientRect();

if(rect.top == 0 && 
  rect.bottom == 0 && 
  rect.left == 0 && 
  rect.right == 0 && 
  rect.width == 0 && 
  rect.height == 0 && 
  rect.x == 0 && 
  rect.y == 0)
{
  alert('hidden');
}
else
{
  alert('visible');
}
于 2021-06-17T13:23:24.557 回答
2

为了详细说明每个人的好答案,这里是Mozilla Fathom 项目中使用的实现

/**
 * Yield an element and each of its ancestors.
 */
export function *ancestors(element) {
    yield element;
    let parent;
    while ((parent = element.parentNode) !== null && parent.nodeType === parent.ELEMENT_NODE) {
        yield parent;
        element = parent;
    }
}

/**
 * Return whether an element is practically visible, considering things like 0
 * size or opacity, ``visibility: hidden`` and ``overflow: hidden``.
 *
 * Merely being scrolled off the page in either horizontally or vertically
 * doesn't count as invisible; the result of this function is meant to be
 * independent of viewport size.
 *
 * @throws {Error} The element (or perhaps one of its ancestors) is not in a
 *     window, so we can't find the `getComputedStyle()` routine to call. That
 *     routine is the source of most of the information we use, so you should
 *     pick a different strategy for non-window contexts.
 */
export function isVisible(fnodeOrElement) {
    // This could be 5x more efficient if https://github.com/w3c/csswg-drafts/issues/4122 happens.
    const element = toDomElement(fnodeOrElement);
    const elementWindow = windowForElement(element);
    const elementRect = element.getBoundingClientRect();
    const elementStyle = elementWindow.getComputedStyle(element);
    // Alternative to reading ``display: none`` due to Bug 1381071.
    if (elementRect.width === 0 && elementRect.height === 0 && elementStyle.overflow !== 'hidden') {
        return false;
    }
    if (elementStyle.visibility === 'hidden') {
        return false;
    }
    // Check if the element is irrevocably off-screen:
    if (elementRect.x + elementRect.width < 0 ||
        elementRect.y + elementRect.height < 0
    ) {
        return false;
    }
    for (const ancestor of ancestors(element)) {
        const isElement = ancestor === element;
        const style = isElement ? elementStyle : elementWindow.getComputedStyle(ancestor);
        if (style.opacity === '0') {
            return false;
        }
        if (style.display === 'contents') {
            // ``display: contents`` elements have no box themselves, but children are
            // still rendered.
            continue;
        }
        const rect = isElement ? elementRect : ancestor.getBoundingClientRect();
        if ((rect.width === 0 || rect.height === 0) && elementStyle.overflow === 'hidden') {
            // Zero-sized ancestors don’t make descendants hidden unless the descendant
            // has ``overflow: hidden``.
            return false;
        }
    }
    return true;
}

它检查每个父母的不透明度、显示和矩形。

于 2020-12-28T06:58:46.013 回答
0

这是我编写的代码,用于查找几个相似元素中唯一可见的元素,并在没有 jQuery 的情况下返回其“类”属性的值:

  // Build a NodeList:
  var nl = document.querySelectorAll('.myCssSelector');

  // convert it to array:
  var myArray = [];for(var i = nl.length; i--; myArray.unshift(nl[i]));

  // now find the visible (= with offsetWidth more than 0) item:
  for (i =0; i < myArray.length; i++){
    var curEl = myArray[i];
    if (curEl.offsetWidth !== 0){
      return curEl.getAttribute("class");
    }
  }
于 2015-08-25T04:01:20.057 回答
-1

这是一种为所有 css 属性(包括可见性)确定它的方法:

html:

<div id="element">div content</div>

CSS:

#element
{
visibility:hidden;
}

javascript:

var element = document.getElementById('element');
 if(element.style.visibility == 'hidden'){
alert('hidden');
}
else
{
alert('visible');
}

它适用于任何 css 属性,并且用途广泛且可靠。

于 2014-11-15T01:41:35.163 回答
-1

这就是我所做的:

HTML & CSS:默认隐藏元素

<html>
<body>

<button onclick="myFunction()">Click Me</button>

<p id="demo" style ="visibility: hidden;">Hello World</p> 

</body>
</html> 

JavaScript:添加了检查可见性是否隐藏的代码:

<script>
function myFunction() {
   if ( document.getElementById("demo").style.visibility === "hidden"){
   document.getElementById("demo").style.visibility = "visible";
   }
   else document.getElementById("demo").style.visibility = "hidden";
}
</script>
于 2018-05-27T09:18:36.440 回答
-2

我正在使用这个。对我来说很好。

var element= document.getElementById('elementId');

if (element.style.display == "block"){

<!-- element is visible -->

} else {

<!-- element is hidden-->

}
于 2022-01-10T22:47:05.570 回答