jQuery .toggleClass() 转换

标签 jquery css css-transitions toggleclass

我正在编写一个 jQuery 脚本,使用 .toggleClass() 更改悬停时 img 的不透明度 该类的 css 是:

.img-hover{
    opacity: 0.5;
    transition: opacity 1s;
}

问题是当我移除鼠标时,我希望它转换回原来的不透明度,但由于切换类,它突然发生,我的代码是

$(document).ready(function () {
    $(".port-item-img").hover(function () {
        $(this).toggleClass('img-hover');
    });
});

有什么想法吗?

我知道这一切都可以用 css 自己完成,但我正在努力插入自己使用 jQuery 学习新东西,因为我对它很陌生并且喜欢挑战

最佳答案

仅使用 jQuery 的解决方案(无需额外的 CSS 样式)。

.animate()提供元素的动画,并且.stop()用于在添加新动画之前停止当前动画(如果仍在处理中)。

JSFiddle .

$(document).ready(function()
{
    $(".port-item-img").hover
    (
        function()
        {
            $(this).stop().animate({ opacity: 0.5 }, 1000);
        },
        function()
        {
            $(this).stop().animate({ opacity: 1 }, 1000);
        }
    );
});

关于jQuery .toggleClass() 转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26154952/

相关文章:

jquery选择最接近的div

javascript - 如何计算jquery中的鼠标滚轮滚动

jquery - 不透明度转换(由额外的类触发)不能向后工作

当鼠标提前离开元素时,CSS 过渡步骤失败

javascript - 如何将属性值调用到javascript

javascript - jquery 将数组分成 4 组

html - 将背景从 JS 更改为 CSS

css - IE 7 DIV 右移

css - Safari 不能旋转超过 360 度

javascript - jQuery </div> 标签导致 NS_ERROR_XPC_BAD_CONVERT_JS