Javascript 可以通过动态更改不透明度来确定元素的目标吗?

Javascript 可以通过动态更改不透明度来确定元素的目标吗?,javascript,jquery,Javascript,Jquery,通过在jQuery中使用函数,以及我的HTML和CSS,我得到了一系列不同颜色的div,这些div改变了它们的不透明度,看起来就像不透明div从左向右移动一样。我希望用户能够单击一个红色按钮,在他/她选择的正方形上停止动画。现在我可以让动画停止(尽管在它完成排队的动画之后),但是我很难让不透明度为1的正方形(在单击按钮时)保持不透明度1。任何帮助都将不胜感激 这是一个jsfiddle })) JQuery.stop()函数可帮助您停止动画。我知道这不是解决你问题的最佳方案,因为你的不透明度只在很

通过在jQuery中使用函数,以及我的HTML和CSS,我得到了一系列不同颜色的div,这些div改变了它们的不透明度,看起来就像不透明div从左向右移动一样。我希望用户能够单击一个红色按钮,在他/她选择的正方形上停止动画。现在我可以让动画停止(尽管在它完成排队的动画之后),但是我很难让不透明度为1的正方形(在单击按钮时)保持不透明度1。任何帮助都将不胜感激

这是一个jsfiddle

}))

JQuery.stop()函数可帮助您停止动画。我知道这不是解决你问题的最佳方案,因为你的不透明度只在很短的时间内保持“1”

    $('#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');
        }
      });
    });

你可能需要这样的东西:

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"))
    }
}


这是处理对象的优点,一种可读性强、简单有序的方法。

我将采用一种不同且不太复杂的方法。也许它的性能更好

演示

这就是全部代码。我使用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;
});

在这些元素和目标上使用
数据不透明度
属性可能更容易,因为该值显然需要随实际不透明度一起更新
$('.game square[data=opacity=“0.2”]”)
this.squares.length
应该是
this.squares.length-1
,除非您希望一帧没有动画正方形。我的意思是,要么是那样,要么是
this.current>=this.squares.length
哇!这种简单的方式真是太棒了!非常感谢你!你知道我是否有办法检索动画停止的方块的类别(颜色)?我想将该方块的类别分配给页面上的另一个div。我一直试图用
.split(“”)[0]
找到它,但是没有用。我非常感谢你的帮助,穆罕默德·乌默!非常感谢。
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;
});