Javascript:使用切换按钮隐藏和显示div标记 [英] Javascript: Hiding and Showing div tag with a toggle button

查看:166
本文介绍了Javascript:使用切换按钮隐藏和显示div标记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会得到它:

我需要做的是隐藏一个特定的div,按下一个按钮,它应该是一个切换,所以基本上:按一次隐藏,再次按下显示,再次按下来隐藏等...

What I need to do is hide a particular div with the press of a button, and it's supposed to be a toggle, so basically: Press once to hide, press again to show, press again to hide etc...

我想要隐藏/显示规则在CSS和纯javascript的交互(没有jquery请)。这是我需要做的,但我不太确定如何执行JavaScript代码。

I want the hide/show rules to be done in CSS and the interaction in pure javascript (no jquery please). Well this is what I need to do, but I'm not quite sure how to execute the javascript code.

html:

<p class="button">Show/hide<p>

<div> I want to hide this by pressing the button above</div>

css:

#showhide {
     display: none;
}

.button {
    display: block;
    height: 30px;
    width: 100px;
    background: green;
    text-align: center;
    padding-top: 10px;
    padding-left: 0px;
    font: 15px arial bold;
    border: 1px solid black;
    text-decoration: none;
    list-style:none;
    margin: 10px 0px 10px 0px;
}

http://jsfiddle.net/fyUJc/14/

此外,如果您认为此问题不属于

Also, if you think this question doesn't belong here or is stupid, please try to refrain from being rude, I'm just trying to learn here.

推荐答案

你可以使用使用 onclick 方法。将您的HTML设为:

You can make use an onclick method. Have your HTML as:

<p class="button" onclick="toggle_visibility('hideMe')">Show/hide</p>
<div id="hideMe">I want to hide this by pressing the button above</div>

并具有以下JavaScript:

And have the following JavaScript:

function toggle_visibility(id) 
{
    var e = document.getElementById(id);
    if (e.style.display == 'block' || e.style.display=='')
    {
        e.style.display = 'none';
    }
    else 
    {
        e.style.display = 'block';
    }
}

DEMO

这篇关于Javascript:使用切换按钮隐藏和显示div标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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