我试图有一个图标,当父 div 悬停时切换类。 到目前为止,这是我的代码:
var actionIcon = document.querySelector(".task > svg")
var taskContainer = document.querySelector(".task")
function iconScale() {
actionIcon.classList.toggle('big');
}
taskContainer.onmouseenter = iconScale
taskContainer.onmouseleave = iconScale
和 HTML:
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
<path d="..." />
</svg>
</div>
我的问题是,我试图实现的效果仅发生在第一个父元素上,而没有发生在其他元素上。 我很确定我没有指定某些内容,但我不知道是什么。有人可以给我提示吗?
最佳答案
修复了映射到所有任务 div 的代码。无法使用 querySelector,因为它只返回第一个实例。
const actionIcon = (parent) => {
return parent.querySelector('svg');
};
document.addEventListener('DOMContentLoaded', function() {
// Add events to ALL divs that conform
let tasks = document.getElementsByClassName('task');
for(let t of tasks) {
t.onmouseenter = iconScale;
t.onmouseleave = iconScale;
}
function iconScale(event) {
let icon = actionIcon(event.target);
icon.classList.toggle('big');
}
});
svg {
height: 50px;
width: 50px;
background-color: red;
}
.big {
background-color: blue;
}
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
<div class="task">
<h3>Title</h3>
<svg viewBox="0 0 24 24">
</svg>
</div>
关于javascript - 使用 Javascript 转换悬停时的子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54000057/