我在W3学校发现了以下内容。所以我想要模态显示点击H1标签。我怎么能这么做?
我对js知之甚少,但我认为我需要用onclick函数触发事件。要做到这一点,我需要为事件指定正确的位置。但我不知道怎么做。
所以,我想是这样的。
我首先需要分配一些代码来获取h-tag,然后为我使用的h1类分配一个id。然后,我需要得到的模式由ide。之后,我需要得到H1标签(这我不知道如何做)。
我在网上搜索了很多东西,我自己也尝试了很多东西,但如果不知道该怎么做就不容易了。
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal"></div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
发布于 2018-08-07 15:24:01
以下是几件事:
close
在你提供的HTML代码上初始化。因此,你的JS代码会抛出一个错误。onclick
属性添加事件侦听器。相反,你应该使用DOM-2等效项的addEventListener
功能。这样,你就可以在同一个元素上添加相同事件的多个侦听器。<h1>
就像你为了<button>
标签:
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
var someTitle = document.getElementById("someTitle");
var span = document.getElementsByClassName("close")[0];
// The function that shows the modal
function showModal() {
modal.style.display = "block";
}
// the function that hides the modal
function hideModal() {
modal.style.display = "none";
}
// adding event listers :
btn.addEventListener("click", showModal);
someTitle.addEventListener("click", showModal);
span.addEventListener("click", hideModal);
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<h1 id="someTitle">Open Modal</h1>
<!-- The Modal -->
<div id="myModal" class="modal">Modal Content</div>
<span class="close">Close</span>
https://stackoverflow.com/questions/-100005927
复制相似问题