简体   繁体   English

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

[英]Toggle (show/hide) element with javascript

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? 也许如果&其他?

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 inline or inline-block elements, or if you are using non-default values for display on elements...such as setting a div's display to "inline" (for whatever reason) and then trying to use this function 如果您隐藏/显示inlineinline-block元素, 或者您使用非默认值在元素上display ,例如将div的display设置为“inline”(对于“内联”,则不会完全万无一失无论什么原因)然后尝试使用此功能

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'
    }
}

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";
}

} }

Here is an alternate solution. 这是另一种解决方案。 Instead of using document.getElementById , you can also use document.querySelector which returns the first Element within the document that matches the specified selector, or group of selectors. 您也可以使用document.querySelector而不是使用document.getElementById ,它返回文档中与指定选择器或选择器组匹配的第一个Element

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";
    }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM