我正在编写一个jQuery脚本,它可以在悬停时改变img的不透明度,类的css是:
.img-hover{
opacity: 0.5;
transition: opacity 1s;
}
它的问题是当我移除鼠标时,我希望它能转换回原来的不透明度,但是由于切换类的原因,它突然发生了,我的代码是
$(document).ready(function () {
$(".port-item-img").hover(function () {
$(this).toggleClass('img-hover');
});
});
有什么想法吗?
我知道这一切都可以用css自己完成,但我正努力用jQuery来学习新东西,因为我对它很陌生,喜欢挑战。
发布于 2014-10-01 21:45:55
只有jQuery的解决方案(没有附加的CSS样式)。
.animate()提供元素的动画,.stop()用于在添加新动画之前停止当前动画(如果它仍在处理中)。
$(document).ready(function()
{
$(".port-item-img").hover
(
function()
{
$(this).stop().animate({ opacity: 0.5 }, 1000);
},
function()
{
$(this).stop().animate({ opacity: 1 }, 1000);
}
);
});
发布于 2014-10-01 21:37:26
为了让它慢下来,你应该:
JS
$(document).ready(function() {
$(".port-item-img").hover(function() {
$(this).addClass('img-hover');
$(this).removeClass('img-unhover');
}, function() {
$(this).removeClass('img-hover');
$(this).addClass('img-unhover');
});
});
CSS
.img-unhover{
opacity: 1;
transition: opacity 1s;
}
发布于 2014-10-01 21:38:37
问题可能是,当类被删除时,transition
属性也丢失了。
jQuery(function($) {
$(".port-item-img").hover(function() {
$(this).toggleClass('img-hover');
});
});
.img-hover {
opacity: 0.5;
}
.port-item-img {
transition: opacity 3s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="port-item-img">port-item-img</div>
<div class="port-item-img">port-item-img</div>
<div class="port-item-img">port-item-img</div>
https://stackoverflow.com/questions/26154952
复制相似问题