我目前正在做一个小元素,其中有几个带有 img、h1 标签和 p 标签的 div 元素。它们每个都有相同的类名,我想做的是给它放置一些 css 效果,以便 h1 标签和 p 标签滑入框架并在我将鼠标悬停在它们所在的 div 元素上时变得可见。
这里的问题是,当我只希望当前悬停的 div 元素具有这种效果时,我正在使用的代码对所有 div 元素产生这种效果。
这是我的代码:
CSS
<style>
.col-md-4 {
margin-top: 30px;
margin-bottom: 26px;
color: white;
}
.title-1 {
margin-top: -260px;
text-align: center;
position: relative;
top: -104px;
opacity: 0;
transition: top 1s, opacity 1s;
}
.paragraph-1 {
margin-top: 160px;
text-align: center;
position: relative;
top: 60px;
opacity: 0;
transition: top 1s, opacity 1s;
}
.title-2 {
margin-top: -260px;
text-align: center;
position: relative;
top: -20px;
opacity: 1;
transition: top 1s, opacity 1s;
}
.paragraph-2 {
margin-top: 160px;
text-align: center;
position: relative;
top: -20px;
opacity: 1;
transition: top 1s, opacity 1s;
}
这是jquery代码
<script>
$('document').ready(function() {
$('.col-md-4').mouseover(function() {
$('h1').addClass('title-2');
$('h1').removeClass('title-1');
$('p').addClass('paragraph-2');
$('p').removeClass('paragraph-1');
});
$('.col-md-4').mouseleave(function() {
$('h1').addClass('title-1');
$('h1').removeClass('title-2');
$('p').addClass('paragraph-1');
$('p').removeClass('paragraph-2');
});
});
</script>
这是 html 的样子
<div class="col-md-4">
<img src="images/remodeling3.jpg" class="img">
<h1 class="title-1">Title Here</h1>
<p class="paragraph-1">Paragraph here.</p>
</div>
<div class="col-md-4">
<img src="images/remodeling3.jpg" class="img">
<h1 class="title-1">Title Here</h1>
<p class="paragraph-1">Paragraph here.</p>
</div>
<div class="col-md-4">
<img src="images/remodeling3.jpg" class="img">
<h1 class="title-1">Title Here</h1>
<p class="paragraph-1">Paragraph here.</p>
</div>
<div class="col-md-4">
<img src="images/remodeling3.jpg" class="img">
<h1 class="title-1">Title Here</h1>
<p class="paragraph-1">Paragraph here.</p>
</div>
<div class="col-md-4">
<img src="images/remodeling3.jpg" class="img">
<h1 class="title-1">Title Here</h1>
<p class="paragraph-1">Paragraph here.</p>
</div>
<div class="col-md-4">
<img src="images/remodeling3.jpg" class="img">
<h1 class="title-1">Title Here</h1>
<p class="paragraph-1">Paragraph here.</p>
</div>
我知道我想使用 this 关键字来定位当前选定的元素,但我只是不知道如何使用我编写的代码来获得我想要的效果。任何帮助都会非常有帮助。
最佳答案
你的脚本应该像
<script>
$('document').ready(function() {
$('.col-md-4').mouseover(function() {
$(this).find('h1').addClass('title-2');
$(this).find('h1').removeClass('title-1');
$(this).find('p').addClass('paragraph-2');
$(this).find('p').removeClass('paragraph-1');
});
$('.col-md-4').mouseleave(function() {
$(this).find('h1').addClass('title-1');
$(this).find('h1').removeClass('title-2');
$(this).find('p').addClass('paragraph-1');
$(this).find('p').removeClass('paragraph-2');
});
});
</script>
关于影响所有元素而不是一个元素的 Jquery 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44542186/