我在画布中用 for 循环生成 5 个圆圈,我想给它们一个类,这样我就可以用 jquery 控制它们,但我做错了。你们能弄清楚发生了什么事吗?
var stage;
var quantity = 6,
width = 60,
height = 60,
circles = [];
function init(){
stage = new createjs.Stage("myCanvas");
stage.width = 500;
stage.height = 600;
createjs.Ticker.setFPS(60);
createjs.Ticker.addEventListener("tick", onTick);
setupGame();
}
function setupGame() {
for(var i = 0; i < quantity; i++) {
var circle = document.createElement("img");
circle.setAttribute('src', 'images/circles/circle'+i+'.png');
circle.className = "circle";
circle.style.position = "absolute";
circle.style.left = Math.floor((Math.random() * 100)) + "%";
circle.style.top = Math.floor((Math.random() * 100)) + "%";
circle.style.width = width + "px";
circle.style.height = height + "px";
document.body.appendChild(circle);
circles.push(circle);
}
}
function onTick(e){
stage.update(e);
}
新版本。在 JonnyD 的帮助下,我现在有了一个功能循环。唯一的问题是图像被附加到身体上,而不是我的舞台上。我尝试过 stage.appendChild(circle),但它不起作用。
这是一个在线资源的链接,大家可以查看=LINK
你的代码有很多问题。
您正在尝试向数组中的字符串添加属性,这是不可能的。使用点或括号表示法将属性添加到对象中。
点符号
foo.bar.baz
方括号表示法
foo['bar']['baz']
我认为你想要做的是在“屏幕”上创建五个圆圈或更技术上正确的 DOM (https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model)在随机位置,设置 H&W 为 60px,类名为 myClass..
我已经为您重写了您的代码,如果您愿意,您可以删除样式 javascript 行并将它们添加到 CSS 中。您真正做错的只是尝试将属性添加到数组值,代码技术错误并丢失了。样式位于宽度、高度之前。Note您仅将 classNames 以及宽度和高度属性添加到 DOM 元素。
您现在可以通过 for 循环和 Circles 数组访问各个圆圈or通过将第 n 个子级选择器与 CSS 结合使用。e.g.circle:nth-child(1) {动画/过渡}
var quantity = 5,
width = 60,
height = 60
circles = [];
function setUp() {
for(var i = 0; i < quantity; i++) {
var circle = document.createElement("div");
circle.className = "circle";
circle.style.position = "absolute";
circle.style.left = Math.floor((Math.random() * 100)) + "%";
circle.style.top = Math.floor((Math.random() * 100)) + "%";
circle.style.backgroundColor = "black";
circle.style.width = width + "px";
circle.style.height = height + "px";
circles.push(circle);
document.body.appendChild(circle);
}
}
setUp();
.circle {
border-radius: 50%;
-webkit-border-radius: 50%;
-moz-border-radius: 50%;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)