【问题标题】:jquery animate only opacity left to rightjquery动画只从左到右不透明度
【发布时间】:2014-01-26 00:21:15
【问题描述】:

是否可以仅对不透明度进行动画处理,并使其沿 div 的方向移动?比如说从左到右?

到目前为止,这是我的代码:只是遗漏了一些“左”的东西,如果它甚至可行的话:

$(document).ready(function() {
    $('#box').mouseenter(function() {
        $(this).animate({opacity: ".5"}, 500);
    });
});

【问题讨论】:

    标签: jquery jquery-animate opacity


    【解决方案1】:

    您可以使用 CSS linear-gradient 属性,然后运行动画循环来改变它的变化位置。这是一个快速的JS Fiddle 显示效果。

    基本思想是根据动画进度设置CSS。例如,使用渐变为透明的白色背景,在完成 25% 时,您将拥有:

    background: linear-gradient(to right,
      rgba(255, 255, 255, 1) 0%,
      rgba(255, 255, 255, 0.25) 25%,
      rgba(255, 255, 255, 0) 100);
    

    在后续步骤中,将 0.25 和 25% 更改为当前进度百分比。小提琴中的 Javascript 看起来像:

    var $child = $('#child');
    var steps = 100;
    var interval = 20;
    var step = 0;
    var animationStep = function() {
        if( step >= steps ) return;
        ++step;
        var progress = step / steps;
        var progressPercent = Math.floor(progress*100) + '%';
        $child.css('background',
            'linear-gradient(to right, ' +
                'rgba(255,255,255,1) 0%, ' +
                'rgba(255,255,255,' + progress + ') ' + progressPercent + ', ' +
                'rgba(255,255,255,0) 100%)'
        );
        setTimeout(animationStep, interval);
    };
    animationStep();
    

    您可以将其调整为在颜色、重用多个元素等方面更通用,但这应该为您提供基本概念。

    【讨论】:

    • 谢谢杰克!比我想象的要复杂得多,但它确实有效。
    • 不客气。我刚刚用一个更好的版本更新了答案,它将完全不透明。原件完成后仍有一定的透明度。
    • +1 伪装不透明度的好方法
    【解决方案2】:

    <head>
        <meta charset="utf-8">
    
        <title>Animation</title>
    
        <script src="js/jquery-2.0.3.min.js"></script>
    </head>
    
    <body>
        <div id="mydiv" style="height:20px; width:49px; opacity:0.5; background-color:green;">
        </div>
    
        <script>
            $('#mydiv').hover(
                function(){
                    $(this).animate({height:40,width:200,opacity:1});
                },
                function(){
                    $(this).animate({height:20,width:100,opacity:0.5});
                }
            );
        </script>
    </body>
    

    【讨论】:

    • 感谢您的回答。然而,这只是扩大了盒子,我正在寻找从左到右在 div 中改变的不透明度。
    猜你喜欢
    • 2011-08-03
    • 1970-01-01
    • 2017-08-29
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多