Javascript 在点击时显示元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4357291/
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
Javascript show element on click
提问by Cyber Junkie
I'm trying to do this without Jquery. I want to show a div when clicking a trigger. So far I have this to hide the element.
我正在尝试在没有 Jquery 的情况下执行此操作。我想在单击触发器时显示一个 div。到目前为止,我有这个来隐藏元素。
document.getElementById('element').style.display = 'none';
HTML..
HTML..
<div class="element">Ahem, boo!!</div>
<a href="#" id="showDiv">Show</a>
How do I create a function to show the div when clicking the link? I would like to avoid using functions like onclick="showDiv()
in the link itself.
单击链接时如何创建一个显示 div 的函数?我想避免使用onclick="showDiv()
链接本身的功能。
回答by Phrogz
document.getElementById('showDiv').onclick=function(){
// Remove any element-specific value, falling back to stylesheets
document.getElementById('element').style.display='';
};
回答by PleaseStand
It's possible to attach event handlers completely within JavaScript. Example:
可以在 JavaScript 中完全附加事件处理程序。例子:
document.getElementById('showDiv').onclick = function() {
// Do whatever now that the user has clicked the link.
};
To reverse the effect of the first line of code you posted, you could use:
要反转您发布的第一行代码的效果,您可以使用:
document.getElementById('element').style.display = 'block'; // or
document.getElementById('element').style.display = '';
回答by Krisi Suci
Add this to the script:
将此添加到脚本中:
function myFunction() {
var btn = document.getElementById("myButton");
//to make it fancier
if (btn.value == "Click To Open") {
btn.value = "Click To Close";
btn.innerHTML = "Click To Close";
}
else {
btn.value = "Click To Open";
btn.innerHTML = "Click To Open";
}
//this is what you're looking for
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
and edit the button and div:
并编辑按钮和div:
<button onclick="myFunction()" id="myButton" value="Click To Open Instructions">Click To Open Instructions</button>
<div style="display:none;" id="myDIV">
</div>