当我在.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');
});发布于 2017-06-17 19:40:28
这对$(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');
});发布于 2017-06-17 19:40:16
将.top和.bottom的选择器更改为$(this).find('.top')和$(this).find('.bottom')。
这在事件处理程序的上下文中是事件发生的元素。
发布于 2017-06-17 19:43:29
您可以尝试使用$(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');
});https://stackoverflow.com/questions/44608660
复制相似问题