[英]Click event not returning the correct element properly
I am trying to create a card that rotates on click.我正在尝试创建一张在点击时旋转的卡片。 It is working but I want to use the
onclick
event to add the 'is-flipped' class to the classlist of div.card.它正在工作,但我想使用
onclick
事件将“is-flipped”class 添加到 div.card 的类列表中。 When I console log the event it shows target as <div class="card__face card__face--front">front</div>
and currentTarget as null. I thought this was due to absolute positioning so I tried z-index: 100 still not working.当我在控制台记录事件时,它显示目标为
<div class="card__face card__face--front">front</div>
和 currentTarget 为 null。我认为这是由于绝对定位,所以我尝试了 z-index: 100 仍然没有在职的。 Why is this happening and how can I get the.card div.为什么会这样,我怎样才能得到.card div。
// var card = document.querySelector(".card"); // card.addEventListener("click", function () { // card.classList.toggle("is-flipped"); // }); function handleCardClick(e) { // e.stopPropagation(); console.log(e); }
* { box-sizing: border-box; margin: 0; padding: 0; } body { font-family: "Poppins", sans-serif; } body { font-family: sans-serif; }.wrapper { width: 200px; height: 260px; border: 1px solid #ccc; margin: 40px 0; perspective: 600px; }.card { width: 100%; height: 100%; transition: transform 1s; transform-style: preserve-3d; cursor: pointer; position: relative; z-index: 100; }.card.is-flipped { transform: rotateY(180deg); }.card__face { position: absolute; width: 100%; height: 100%; line-height: 260px; color: white; text-align: center; font-weight: bold; font-size: 40px; -webkit-backface-visibility: hidden; backface-visibility: hidden; }.card__face--front { background: red; }.card__face--back { background: blue; transform: rotateY(180deg); }
<div class="wrapper"> <div class="card" onclick="handleCardClick(event)"> <div class="card__face card__face--front">front</div> <div class="card__face card__face--back">back</div> </div> </div> <div class="main" onclick="handleCardClick(event)">123456789</div>
in order to manipulate with classes on 'card' element try:为了使用“card”元素上的类进行操作,请尝试:
const card = document.querySelector('.card');
card.addEventListener('click', function(){
card.classList.toggle('is-flipped')
})
if you want to use onclick="" then you should add "pointer-events: none;"如果你想使用 onclick="" 那么你应该添加 "pointer-events: none;" property to.card child elements
属性 to.card 子元素
.card__face {
pointer-events: none;}
and和
function handleCardClick(e) {
const currentEl = e.target;
currentEl.classList.toggle('is-flipped')}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.