以下代码有效,但我遇到了一个问题,因为我想要有多个像这样的投资组合对象。如果我使用当前的代码,它将引发所有带有文本的隐藏 div (.slide),而不是基于悬停一次一个。我不能使用“this”,因为那只会使图片向上动画。我可以给出所有内容的 id 并编写大量重复的 JavaScript 代码,但我几乎肯定这不是最好的做事方式。
基本上,您如何以具有悬停效果的 div 为目标,导致另一个 div 执行某些操作,并且仍然能够重用代码?
此部分的 HTML:
<div class="col-md-6 high">
<img class="port" src="http://loremflickr.com/320/240" alt="test">
<div class="slide">
<h3>Test Portfolio</h3>
</div>
</div>
本部分的 CSS:
.high {
height: 200px;
overflow: hidden;
}
.port {
width: 100%;
height: 200px;
}
.slide {
background-color: rgba(74, 170, 165, 0.7);
color: white;
position: relative;
top: -34px;
height: 200px;
width: 100%;
padding: 20px;
text-align: center;
}
本节的 JavaScript:
$(document).ready(function(){
var portfolio = {
// moves div with text over portfolio picture on hover
hoverPort: function() {
$(".port").hover(function() {
$(".slide").stop().animate({"top" : "-110px"});
}, function() {
$(".slide").stop().animate({"top" : "-34"});
});
}, // end of hoverPort function
} // end of portfolio object
portfolio.hoverPort();
}); // end of document.ready
最佳答案
当然,您可以使用 this
,不是为元素本身设置动画,而是基于此引用另一个“最接近”的元素:
$(".port").hover(function() {
$(this).next('.slide').stop().animate({"top" : "-110px"});
}, function() {
$(this).next('.slide').stop().animate({"top" : "-34"});
});
演示片段
$(".port").hover(function() {
$(this).next('.slide').stop().animate({
"top": "-110px"
});
}, function() {
$(this).next('.slide').stop().animate({
"top": "-34"
});
});
.col-md-6 {
float: left;
width: 50%;
padding:25px;
box-sizing:border-box;
}
.slide {
position: relative;
top: -60px;
color: white;
background: red;
font-size: 2em;
font-family: sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-6 high">
<img class="port" src="http://loremflickr.com/320/240" alt="test">
<div class="slide">
<h3>Test Portfolio</h3>
</div>
</div>
<div class="col-md-6 high">
<img class="port" src="http://loremflickr.com/320/240" alt="test">
<div class="slide">
<h3>Test Portfolio</h3>
</div>
</div>
关于javascript - 多个 Div 的动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37799439/