2017-04-04 143 views
0

我正在使用javascript通过单击按钮显示隐藏的div。显示在div之后,我希望能够再次单击该按钮,隐藏DIV,等等...使用javascript显示后隐藏div

这里是我的javascript:

<script type="text/javascript"> 
function showDiv() { 
    document.getElementById('dropdownText').style.display = "block"; 
} 
</script> 

这是按钮:

<input type="button" name="answer" value="+" onclick="showDiv()" /> 

这是隐藏的div:

<div id="dropdownText" style="display:none;"> 
    This is the dropdown text. 
</div> 
+1

而你的问题是......?你真的在使用jQuery吗? – j08691

+0

那么你有什么尝试,你卡在哪里? – Steve

+0

'if(... style.display =='block')...''' –

回答

2

你可以如将指定的类绑定到元素并将其切换。

function showDiv() { 
 
    document.getElementById('dropdownText').classList.toggle("hidden"); 
 
}
.hidden { 
 
    display: none; 
 
}
<input type="button" name="answer" value="+" onclick="showDiv()" /> 
 
This is the hidden div: 
 

 
<div id="dropdownText" class='hidden'> 
 
    This is the dropdown text. 
 
</div>

0

您只需要做到这一点:

const drop = document.getElementById('dropdownText') 
 

 
const toggleDropdown = _ => { 
 
    const cl = drop.classList 
 
    cl.contains('hide')?cl.remove('hide'):cl.add('hide') 
 
}
#dropdownText.hide {display:none} 
 

 

 
/* DropDown Styles for this demo */ 
 
#dropdownText {width: 10em; height: 4em; background: green}
<button onclick='toggleDropdown()'>Toggle Div</button> 
 
<div id='dropdownText'></div>

注:点击Run Code Snippet在行动中看到的代码。


它的工作方式是通过检测是否有隐藏类此基础上,拨动这个类。

实际隐藏和显示是通过CSS完成的!

1

如果标记与jQuery这个问题为好,所以我想你可以使用.toggle功能,这样的 -

$('#answer').click(function() { 
    $('#dropdownText').toggle(); 
} 

如果你想用JavaScript只是,你showDiv()函数来撅应该是这样的 -

function showDiv() { 
    let text = document.getElementById('dropdownText'); 
    if (text.style.display === 'none') { 
     text.style.display = 'block'; 
    } 
    else { 
    text.style.display = 'none'; 
    } 
} 

你应该每一个按钮被点击时捕捉当前的风格,因为你想“切换”回相反的状态。

0
<div id="dropdownText" style="display:none"> 
This is the dropdown text. 
</div> 

<script type="text/javascript"> 

function showDiv() { 
    var x = document.getElementById('dropdownText'); 
    if (x.style.display === 'none') { 
     x.style.display = 'block'; 
    } else { 
    x.style.display = 'none'; 
    } 
} 
</script>