当我将鼠标悬停在 .winner-container
上时,JS 函数告诉 .headline
移出 .winner-container
并且它告诉.bottom
移动到 .winner-container
。当我取消悬停时,会发生相反的情况。
问题是,我将拥有数百个这样的容器,所有容器都带有 .winner-container
类。所以我意识到,当我将鼠标悬停在其中一个容器上时,该功能会同时应用于数百个不同的容器。我只希望将函数应用于我悬停的特定容器。我可以通过给每个容器一个 id,然后为每个 id 编写新的 JS 代码来做到这一点,但这需要大量的工作,考虑到会有数百个这样的 div。有没有更优雅的解决方案?
https://jsfiddle.net/6sm6ajht/
HTML
<div class="winner-container">
<div class="top">
<h4 class="headline">SME Example 1</h4>
</div>
<div class="bottom">
<div class="winner-words">
<h6>SME Examle 1 is a technology company.</h6>
<h6><a>Learn more...</a></h6>
</div>
</div>
</div>
<div class="winner-container">
<div class="top">
<h4 class="headline">SME Example 2</h4>
</div>
<div class="bottom">
<div class="winner-words">
<h6>SME Examle 2 is an e-commerce company.</h6>
<h6><a>Learn more...</a></h6>
</div>
</div>
</div>
CSS
.winner-container {
position: relative;
box-shadow: 0px 2.5px 1px 0px rgba(0, 0, 0, 0.25);
border: 1px solid #074E68;
}
.winner-container,
.top,
.bottom {
width: 10em;
height: 12em;
overflow: hidden;
}
.bottom {
position: absolute;
height: 12em;
width: 100%;
top: 12em;
transition: 0.5s ease-in-out;
}
.top .headline {
position: absolute;
top: 2.5em;
width: 100%;
background: rgba(255, 255, 255, 0.8);
box-shadow: 0px 1px 1px 2px rgba(0, 0, 0, 0.1);
transition: 0.5s ease-in-out;
}
.top-up .headline {
top: -2.5em;
}
.bottom-up.bottom {
top: 0em;
background-color: rgba(0, 0, 0, 0.65);
}
JavaScript
$(".winner-container").on("mouseenter", function() {
$(".top").addClass('top-up');
$(".bottom").addClass('bottom-up');
});
$(".winner-container").on("mouseleave", function() {
$(".top").removeClass('top-up');
$(".bottom").removeClass('bottom-up');
});
最佳答案
这对 $(this)
选择器来说是一个很好的机会。因为有许多相同的元素,但您只希望每个事件处理程序引用该特定元素,您可以使用 $(this)
并使用像 .children
这样的相对选择器来定位与 this
元素相关的其他元素。
$(".winner-container").on("mouseenter", function() {
$(this).children(".top").addClass('top-up');
$(this).children(".bottom").addClass('bottom-up');
});
$(".winner-container").on("mouseleave", function() {
$(this).children(".top").removeClass('top-up');
$(this).children(".bottom").removeClass('bottom-up');
});
关于JavaScript - 将函数应用于具有相同类名的 div 集合中的特定 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44608660/