简体   繁体   English

如何使整个 div 可点击?

[英]How to make the whole div clickable?

I have a div with contents in it:我有一个包含内容的div

<div class="block">
    <img src='...'>
    <span>...</span>
</div>

I set up a JavaScript Event Listener when someone clicks on the div :当有人点击div时,我设置了一个 JavaScript 事件监听器:

document.body.addEventListener("click", function(e) {
    if (e.target.tagName === 'DIV' && e.target.classList.contains("block")){
        (code)
    }
}

It works when I click on the area of the div that has no content.当我单击没有内容的div区域时,它可以工作。 But it doesn't works, when I click to the image or to the text.但是,当我单击图像或文本时,它不起作用。
How can I get this at the whole div working?我怎样才能在整个 div 工作时得到这个?

The event.target is the element you clicked on. event.target是您单击的元素。 If you do not directly click on the div then your code will not match your tests because you are clicking on a child element.如果您不直接单击 div,那么您的代码将与您的测试不匹配,因为您正在单击子元素。

So when you are using event delegation and you want to know if an element or one of its children is clicked on, you need to walk up the tree to see if it is that element.因此,当您使用事件委托并想知道是否单击了某个元素或其子元素之一时,您需要向上走一棵树以查看它是否是该元素。 You can do that with closest你可以用closest的来做到这一点

 document.body.addEventListener("click", function(e) { if (e.target.closest('div.block')) { console.log('clicked', Date.now()); } });
 <h2>Example</h2> <div class="block"> <img src='http://placekitten.com/g/200/300'> <span>foo bar kitten</span> </div>

welcome to SO.欢迎来到SO。 You can add the event listener on the div itself and then perform whatever code you like.您可以在 div 本身上添加事件侦听器,然后执行您喜欢的任何代码。 The reason it doesn't work in your case is because you are adding the event listener to the whole body and thus as the event handler is called, it doesn't recognize the elements you are clicking on even if they are inside the div .它在您的情况下不起作用的原因是因为您将事件侦听器添加到整个主体,因此当事件处理程序被调用时,即使它们在div内,它也无法识别您正在单击的元素。

Try this instead:试试这个:

document.querySelector('div#block').addEventListener("click", function(e) {
  // code...
});

Try to give an id to div and add your event listener to that.尝试为 div 提供一个 id 并将您的事件侦听器添加到其中。

<div id="myDiv" class="content">
    // your content goes here
</div>

And in javascript并在 javascript

const myDiv = document.getElementById("myDiv");
myDiv.addEventListener("click", (event) => {
   // your function goes here
})

There are many ways you can do it.有很多方法可以做到这一点。 But In my opinion the best way is to make anything clickable in JS is use onClick() function.但在我看来,最好的方法是让 JS 中的任何东西都可以clickable是使用onClick() function。 You can simply use onClick=functionName()您可以简单地使用onClick=functionName()

 function changeBackground(){ let block = document.getElementsByClassName('block'); block[0].style.backgroundColor = "green"; }
 .block{ height: 50px; border: 1px solid; }
 <div class="block" onClick="changeBackground()"> <div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM