使用 javascript 切换(显示/隐藏)元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13921042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:10:53  来源:igfitidea点击:

Toggle (show/hide) element with javascript

javascripthtmlcss

提问by Onyx G.

By using this method I can show/hide an element by using 2 buttons:

通过使用这种方法,我可以使用 2 个按钮来显示/隐藏元素:

<script type="text/javascript">
function showStuff(id) {
        document.getElementById(id).style.display = 'block';
}
function hideStuff(id) {
    document.getElementById(id).style.display = 'none';
}
</script>

<input type="button" onClick="hideStuff('themes')" value="Hide">
<input type="button" onClick="showStuff('themes')" value="Show">
<div id="themes" style="display:block">
    <h3>Stuff</h3>
</div>

Is there a method to use a single button?? Maybe if & else?

有没有使用单个按钮的方法?也许如果 & 其他?

回答by Ian

You've already answered your question...the use of if/else:

您已经回答了您的问题...使用if/ else

function toggle(id) {
    var element = document.getElementById(id);

    if (element) {
        var display = element.style.display;

        if (display == "none") {
            element.style.display = "block";
        } else {
            element.style.display = "none";
        }
    }
}

This won't be completely foolproof, in case you are hiding/showing inlineor inline-blockelements, orif you are using non-default values for displayon elements...such as setting a div's displayto "inline" (for whatever reason) and then trying to use this function

这不会是完全万无一失的,以防您隐藏/显示inlineinline-block元素,或者如果您display对元素使用非默认值......例如将 div 设置display为“内联”(无论出于何种原因)然后尝试使用这个功能

回答by John

Yes if/else will work

是的,如果/否则会起作用

function toggle(id){
    var elem = document.getElementById(id);
    if(elem.style.display == 'block'){
        elem.style.display == 'none'
    } else if(elem.style.display == 'none'){
        elem.style.display == 'block'
    }
}

回答by SteinAir

I think you mean something like this:

我想你的意思是这样的:

 function toggle(id){
var elem = document.getElementById(id);
if(elem.style.display == "block"){
    elem.style.display="none";
} else {
    elem.style.display="block";
}

}

}

回答by Steffi Keran Rani J

Here is an alternate solution. Instead of using document.getElementById, you can also use document.querySelectorwhich returns the first Elementwithin the document that matches the specified selector, or group of selectors.

这是一个替代解决方案。除了使用document.getElementById,您还可以使用document.querySelectorwhich 返回文档中与指定选择器或选择器组匹配的第一个元素

Solution Code:

解决方案代码:

function toggleShow() {
    var elem = document.querySelector(id);
    if(elem.style.display == 'inline-block'){
      elem.style.display="none";
    }
    else {
      elem.style.display = "inline-block";
    }
  }