[英]Javascript show element on click
I'm trying to do this without Jquery. 我正在尝试没有Jquery的情况。 I want to show a div when clicking a trigger. 我想在单击触发器时显示div。 So far I have this to hide the element. 到目前为止,我有这个隐藏元素。
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? 单击链接时如何创建显示div的函数? I would like to avoid using functions like onclick="showDiv()
in the link itself. 我想避免在链接本身中使用类似onclick="showDiv()
函数。
document.getElementById('showDiv').onclick=function(){
// Remove any element-specific value, falling back to stylesheets
document.getElementById('element').style.display='';
};
It's possible to attach event handlers completely within JavaScript. 可以将事件处理程序完全附加在JavaScript中。 Example: 例:
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 = '';
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.