jquery - 如何使 CSS 更改平滑?

标签 jquery css

我有一张灰度图像,所以当使用 jQuery mouseenter 时,它会变为彩色版本。 这是我的代码...

$(function(){
    $(document).on('mouseenter', '.items', function() {
        img = $(this).data('img');
        img2 = img.replace(".", "C.");
        $(this).css("background-image", "url(img/" + img2 + ")");
    }).on('mouseleave', '.items', function() {
        $(this).css("background-image", "url(img/" + img + ")");
    }); 
});

顺便说一句……问题是这个“过渡/改变”不是很顺利,它像“ Spark ”一样刷新页面时出现。所以这不是一个好的表达方式。 谁能告诉我我该怎么做才能解决这个问题? 谢谢...

最佳答案

可以通过许多不同的方式在图像之间实现平滑过渡,这里有三种...

选项 1:jQuery on 悬停委托(delegate)(对于动态加载的元素)

jsfiddle example

<div id="container">
    <div class="img-transition bw"></div>
    <div class="img-transition color"></div>
</div>
$('body').on('mouseenter', '#container', function() {
    $('.color', this).fadeIn();
}).on('mouseleave', '#container', function() {
    $('.color', this).fadeOut();
});

方案二:jQuery hover事件解决方案(针对动态加载的元素)

jsfiddle example

<div id="container">
    <div class="img-transition bw"></div>
    <div class="img-transition color"></div>
</div>
var $container = $('#container'),
    $color = $('.color');

$container.hover(function() { // mouseover
    $color.fadeIn();
}, function() { // mouseout
    $color.fadeOut();
});

选项 3:CSS3 transition属性

jsfiddle example

<div id="container">
    <div class="img-transition bw"></div>
    <div class="img-transition color"></div>
</div>
.color{
    background-position:-47px -47px;
    opacity: 0;
    -webkit-transition: 400ms linear;
}
.color:hover {
    opacity: 1;
}

transition 很好 support

关于jquery - 如何使 CSS 更改平滑?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19716884/

相关文章:

javascript - jQuery settimeout() 无法正常工作

javascript - 什么是使用 html-php 的母版页

css - Bootstrap 4 卡片 - 让第一张卡片更大

css - 媒体查询内容适配

css - 为什么 minmax(0, 1fr) 对长元素有效而 1fr 却不行?

javascript - 单击更改 CSS,然后在下次单击时再次更改

jQuery:如何获取跨度的内容,减去 1,然后用新数字替换跨度的内容?

javascript - 通过 JavaScript 调整 iFrame 内容大小

php - woocommerce 自定义结帐字段添加费用以订购 ajax

html - 如何反转媒体查询中元素的顺序?