使用javascript切换(显示/隐藏)元素 [英] Toggle (show/hide) element with javascript

查看:105
本文介绍了使用javascript切换(显示/隐藏)元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<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?

推荐答案

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

You've already answered your question...the use of 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";
        }
    }
}

如果你隐藏/显示 inline inline-block 元素,如果您在元素上使用 display 的非默认值,例如将div的显示设置为inline (无论什么原因),然后尝试使用此函数

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

这篇关于使用javascript切换(显示/隐藏)元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆