首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用js的onClick事件html h-tag?

如何使用js的onClick事件html h-tag?
EN

Stack Overflow用户
提问于 2018-08-07 06:00:38
回答 1查看 0关注 0票数 0

我在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>
EN

Stack Overflow用户

发布于 2018-08-07 15:24:01

以下是几件事:

  • 对象没有span标记。close在你提供的HTML代码上初始化。因此,你的JS代码会抛出一个错误。
  • 我强烈建议你不要使用onclick属性添加事件侦听器。相反,你应该使用DOM-2等效项的addEventListener功能。这样,你就可以在同一个元素上添加相同事件的多个侦听器。
  • 事件从DOM树(窗口对象)的顶部传播到目标元素,然后返回到DOM树的顶部。因此,如果在窗口对象上添加单击事件的侦听器,则处理程序将在单击文档的任何位置(包括单击模式div时)被触发。所以,你为隐藏模式而写的代码是行不通的。不幸的是,在JavaScript中检测元素外部的单击不是一件容易的事情。
  • 至于你的问题“,所以我希望模态显示点击H1标签。“,你可以在<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>

票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100005927

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档