如何在使用javascript悬停时向卡中添加元素



当鼠标悬停在卡片上时(如netflix卡片),我试图向卡片添加元素,但当光标移动到新按钮出现的位置时,会触发mouseout事件,并且无法按下按钮。这里有一个例子:

<div class="cards">
<img class="cardsImg" src="codePic.jpg" alt="">
<h3>Project 1</h3>
<div class="cardsDesc"></div>
</div>

和JS:

document.addEventListener('DOMContentLoaded', function () {
let cards = document.querySelectorAll('.cards');
for (let i = 0; i < cards.length; i++) {
cards[i].addEventListener('mouseover', function () {
let desc = cards[i].querySelector('.cardsDesc')
desc.innerHTML = `<div class="readMore" onmouseover="moveArrow('arrow1')" onmouseout="moveArrowBack('arrow1')">
<a href="About.html" class="readMoreLink">Click here to read more <span id="arrow1">&#10132;</span></a>
</div>`;
})
cards[i].addEventListener('mouseout', function () {
let desc = cards[i].querySelector('.cardsDesc')
desc.innerHTML = ``;
})
}
})

我是JavaScript的新手,不知道该尝试什么,所以很感激任何帮助。

尝试使用mouseenter和mouseleave事件。工作示例https://codepen.io/sethuramancbe/pen/poxoreK

function moveArrow(arrow) {
//your code
}
function moveArrowBack(arrow) {
//your code
}
document.addEventListener('DOMContentLoaded', function () {
let cards = document.querySelectorAll('.cards');
for (let i = 0; i < cards.length; i++) {
cards[i].addEventListener('mouseenter', function () {
let desc = cards[i].querySelector('.cardsDesc')
desc.innerHTML = `<div class="readMore" onmouseover="moveArrow('arrow1')" onmouseout="moveArrowBack('arrow1')">
<a href="About.html" class="readMoreLink">Click here to read more <span id="arrow1">&#10132;</span></a>
</div>`;
})
cards[i].addEventListener('mouseleave', function () {
let desc = cards[i].querySelector('.cardsDesc')
desc.innerHTML = ``;
})
}
})
<div class="cards">
<img class="cardsImg" src="codePic.jpg" alt="">
<h3>Project 1</h3>
<div class="cardsDesc"></div>
</div>

let cards = document.querySelectorAll('.cards');
for (let i = 0; i < cards.length; i++) {
let desc = cards[i].querySelector('.cardsDesc');
cards[i].addEventListener('mouseover', function () {
desc.style.display = `block`;
});
cards[i].addEventListener('mouseout', function () {
desc.style.display = 'none';
});
}
<div class="cards">
<img class="cardsImg" src="codePic.jpg" alt="" />
<h3>Project 1</h3>
<div class="cardsDesc" style="display: none">
<div class="readMore">
<a href="About.html" class="readMoreLink">Click here to read more <span id="arrow1">&#10132;</span></a>
</div>
</div>
</div>

这是你的问题的解决方案,你应该这样定义它来实现它。如有任何疑问,请告诉我。非常感谢。

相关内容

  • 没有找到相关文章

最新更新