javascript - 如何阻止其他 div 使用 javascript 进行动画处理?

标签 javascript css animation

我在阻止其他 div 设置动画时遇到问题。我正在制作一个方形闪烁的 div,但每次我添加不需要设置动画的任何其他 div 时,它们也会设置动画。

这是我的代码:

JavaScript

var fadeintime = 500;
var fadeouttime = 1000;
$(document).ready(function(){
setInterval(anim, 50);
});
function anim(){
var rand = Math.floor((Math.random()*$("body").children("div").length));
var el = $("body").children("div")[rand];
$(el).animate({opacity: "0.7"}, fadeintime);
$(el).animate({opacity: "0.1"}, fadeouttime);
} 

html

<div class="squares1"></div><div class="squares2"></div><div class="squares3"></div><div class="squares5"></div><div class="squares3"></div><div class="squares4"></div>... to as many squares i want

CSS

body {
background-color:#222;
    line-height:0;
    overflow:hidden;
    padding:0;
    margin:0;
}
.squares {
    background: none repeat scroll 0 0 #B6FFFF;
    transition: background 1200ms ease-out 0s;
        opacity: 0;
    height: 3em;
width: 50px;
    float:left;
    padding:0;
    margin:0;
}
.squares1 {
    background: none repeat scroll 0 0 #CEFF24;
    transition: background 1200ms ease-out 0s;
        opacity: 0;
    height: 3em;
width: 50px;
    float: left;
    padding:0;
    margin:0;
}
.squares2 {
    background: none repeat scroll 0 0 #BF86FF;
    transition: background 1200ms ease-out 0s;
        opacity: 0;
    height: 3em;
width: 50px;
    float:left;
    padding:0;
    margin:0;
}
.squares3 {
    background: none repeat scroll 0 0 #FF8B24;
    transition: background 1200ms ease-out 0s;
        opacity: 0;
    height: 3em;
width: 50px;
    float:left;
    padding:0;
    margin:0;
}
.squares4 {
    background: none repeat scroll 0 0  #EFFFB6;
    transition: background 1200ms ease-out 0s;
        opacity: 0;
    height: 3em;
width: 50px;
    float:left;
    padding:0;
    margin:0;
}
.squares5 {
    background: none repeat scroll 0 0  #FFBAF2;
    transition: background 1200ms ease-out 0s;
        opacity: 0;
    height: 3em;
width: 50px;
    float: left;
    padding:0;
    margin:0;
}

我认为 javascript 有问题,谁能指出如何阻止其他 div 设置动画?

最佳答案

我认为问题出在这行代码上

var el = $("body").children("div")[rand];

由于这将考虑所有 div 元素,您将无法控制特定的 div。尝试为每个 div 提供 id。

<div class="squares1" id="div1">

关于javascript - 如何阻止其他 div 使用 javascript 进行动画处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23180547/

相关文章:

javascript - jQuery - 如何从文本区域/输入中获取选定的文本?

Javascript递归数据结构定义

javascript - react : Adding an object to an array in state through input fields

javascript - wow.js 的问题

css - 如何使用css从浏览器添加悬停效果

带有查询的 iOS Segue 动画初学者

javascript - 由于奇怪的类型接口(interface),未解决推送方法

html - Google Blogger 的相关文章小工具

javascript - 当元素处于 View 中时(当您滚动到元素时)成帧器运动动画

CSS "fill-mode:forwards"在 Safari 中不工作