我使用鼠标悬停事件将阴影从黑色变为粉红色。但是,当我将 mouse over 事件添加到其他卡上时,它们只会更改第一张卡。如何让每张卡片在悬停时改变颜色?
JS
<script>
function mouseOver() {
document.getElementById("CardHover").style.boxShadow = "-6px 6px 0px 0px #FF8A88";
}
function mouseOut() {
document.getElementById("CardHover").style.boxShadow = "-6px 6px 0px 0px #000";
}
</script>
HTML
<div class="report" id="CardHover" onclick="location.href='#';" onmouseover="mouseOver()" onmouseout="mouseOut()">
<img style="width: 100%; height: 100%; border-radius: 10px;" src="#.png" alt="">
<div style="display: flex; flex-direction: column; align-items: flex-start; gap: 6px; padding: 8px;">
<h6>#ServiceDesign #DesignThinking #Ethnography</h6>
<h4>Title</h4>
<p>Body Copy</p>
<a href="#" class="tertiary">Explore</a>
</div>
</div>
<div class="report" id="CardHover" onclick="location.href='#';" onmouseover="mouseOver()" onmouseout="mouseOut()">
<img style="width: 100%; height: 100%; border-radius: 10px;" src="#.png" alt="">
<div style="display: flex; flex-direction: column; align-items: flex-start; gap: 6px; padding: 8px;">
<h6>#ServiceDesign #DesignThinking #Ethnography</h6>
<h4>Title</h4>
<p>Body Copy</p>
<a href="#" class="tertiary">Explore</a>
</div>
</div>
期望每张卡片都有自己的悬停,使用鼠标悬停在事件上。
代码中的主要问题是因为您在所有卡片元素上重复相同的
id
属性值。这是无效的,因为 id
必须是唯一的。要解决该问题,请将 id
更改为 class
。
话虽这么说,代码中还有很多其他问题需要解决:
onX
属性。前者允许您从 Event 对象获取对引发事件的元素的引用,以便您可以根据需要更新它。mousenter
/mouseleave
而不是 mouseover
。后者对于鼠标在目标元素上移动的每一个像素都会触发一次,这在这个用例中是多余的。
将 CSS 放入外部样式表中,而不是 HTML 中。click
div
。这是因为它对于可访问性非常不利。
// don't repeat ids
// use unobtrusive event handlers, not inline
// use mouseenter/mouseleave, not mouseover
// put CSS in external stylesheet
// do not put click handlers that redirect the page on div elements - bad for accessibility
const cards = document.querySelectorAll('.CardHover');
cards.forEach(card => {
card.addEventListener('mouseenter', e => {
e.target.style.boxShadow = '-6px 6px 0px 0px #FF8A88';
});
card.addEventListener('mouseleave', e => {
e.target.style.boxShadow = '-6px 6px 0px 0px #000';
});
});
.report>img {
width: 100%;
height: 100%;
border-radius: 10px;
}
.report>div {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 6px;
padding: 8px;
}
<div class="report CardHover">
<img src="#.png" alt="">
<div>
<h6>#ServiceDesign #DesignThinking #Ethnography</h6>
<h4>Title</h4>
<p>Body Copy</p>
<a href="#" class="tertiary">Explore</a>
</div>
</div>
<div class="report CardHover">
<img src="#.png" alt="">
<div>
<h6>#ServiceDesign #DesignThinking #Ethnography</h6>
<h4>Title</h4>
<p>Body Copy</p>
<a href="#" class="tertiary">Explore</a>
</div>
</div>