你能否通过动态更改的不透明度来定位一个元素?

3
通过使用jQuery中的函数,以及我的HTML和CSS,我有一系列不同颜色的div,它们的不透明度会改变,从而看起来就像不透明的div从左到右移动。我希望用户能够点击红色按钮,在他/她选择的正方形上停止动画。现在,我可以让动画停止(尽管在完成其排队的动画之后),但我无法让其不透明度为1的正方形在按钮点击时保持不透明度为1。非常感谢任何帮助。
这里是一个jsfiddle:http://jsfiddle.net/seifs4/krm6uenj/
$(document).ready(function () {

$.fn.extend({
    brighten: function(){
        $(this).fadeTo(150, 1);
    }
});
$.fn.extend({
    fade: function(){
        $(this).fadeTo(150, 0.2);
    }
});

function animateSequence() {
    $('.game-square').each(function (i) {
        $(this).delay((i++) * 145).brighten();
        $(this).delay((i++) * 5).fade();
    });
}
animateSequence()
var interval=setInterval(animateSequence, 1700);

$('#red-button').click(function(){

    $('.game-square').each(function(){
        if ($('.game-square', this).not().css('opacity') == 0.2){
        $(this).css('opacity', '1');
        }
    });
    clearInterval(interval);
});

});


可能更容易的方法是在这些元素上设置一个 data-opacity 属性,并根据其值进行目标定位,显然您需要随着实际不透明度更新该值。$('.game-square[data=opacity="0.2"]') - sbeliv01
3个回答

5
你可能需要类似这样的内容:
function animateSequence(){
    this.current = 0;
    this.squares = $(".game-square");
    this.animate = function(){
        this.squares.eq(this.current).fadeTo(150, 1, function(){
            $(this).fadeTo(150, 0.2)
        });
        this.current = this.current >= this.squares.length - 1 ? 0 : this.current + 1;
    };
    this.start = function(){
        this.running = setInterval(this.animate.bind(this), 150)    
    };
    this.stop = function(){
        this.running = clearInterval(this.running);            
        this.squares.eq(this.current).stop().css("opacity",1);
        alert("Current color: " + this.squares.eq(this.current).attr("class"))
    }
}

演示

使用对象的优点在于,它非常易读、简单和有序。


this.squares.length 应该是 this.squares.length - 1,除非你想要一个帧没有动画正方形。 - Jan
我的意思是,要么是 this.current >= this.squares.length - Jan

0
JQuery 的 .stop() 函数可以帮你停止动画。我知道这不是你问题的最佳解决方案,因为你的不透明度只能保持短暂时间。
    $('#red-button').click(function(){
      clearInterval(interval);
      $('.game-square').stop();//this stop the animation
      $('.game-square').each(function(){
        if ($(this).not().css('opacity') > '0.2'){// I changed this logic
            $(this).css('opacity', '1');
        }
      });
    });

0

我会采用一种不同且不那么复杂的方法。也许它甚至有更好的性能。

演示 http://jsfiddle.net/LkatLkz2/8/

这是整个代码。我使用 CSS 实现动画效果,并通过改变透明度来改变类。

var sqrs = $('.game-square'),
    len = sqrs.length,
    i=0,
    looping = true;

setInterval(function(){
    if (!looping) return;
    sqrs.removeClass('full').eq(i).addClass('full');
    i = ++i % len;
},400);


$("#red-button").click(function () {
    looping = !looping;
});

哇!这简直太棒了!非常感谢! - Brian Seifert
你知道我有没有办法获取动画停留在哪个正方形上的类(颜色)吗? - Brian Seifert
我想将该方块的类分配给页面上的另一个div。我一直在尝试使用.split(' ')[0]找到它,但没有成功。 - Brian Seifert
非常感谢你的帮助,Muhammad Umer!谢谢! - Brian Seifert

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接