我知道这个问题可能已经回答了几次,但我似乎无法在我的代码中使用它。对于每个愿意帮助感谢你的人。
我有一个在屏幕上创建一个矩形的对象然后我运行setInerval来重新创建屏幕上的矩形,以便在屏幕上一个接一个地显示许多矩形。
问题:我需要给每个矩形一个ID,我不太了解jquery,如果我在.block上为jquery实现attr,它会改变所有div的所有id。
我希望创建的每个新div都有自己的id示例id = block1,然后下一个div将是id = block2,依此类推,所有这些都是类块。
var cHeight = window.innerHeight - 150; //size of block
var cWidth = window.innerWidth - 150;
var Block = function(block) {
this.block = document.createElement('div');
this.block.className = 'block';
document.body.appendChild(this.block);
}
Block.prototype.coordinates = function(top,left) {
this.block.style.top = top + 'px';
this.block.style.left = left + 'px';
}
Block.prototype.size = function(width,height) {
this.block.style.width = width + 'px';
this.block.style.height = height + 'px';
}
function randomTop() {
var i = Math.random();
var y = (i * (cHeight - 0 + 1)) +0;
var x = Math.floor(y);
return x;
}
function randomLeft() {
var i = Math.random();
var y = (i * (cWidth - 0 + 1)) + 0;
var x = Math.floor(y)
return x;
}
function repeatBlocks() {
block1 = new Block();
block1.size(150,150);
block1.coordinates(randomTop(),randomLeft());
}
setInterval(repeatBlocks,1000);
答案 0 :(得分:0)
您需要添加var id = 1;
然后在Block函数中添加:this.block.id =“block”+ id ++;
$pull
var cHeight = window.innerHeight - 150; //size of block
var cWidth = window.innerWidth - 150;
var id = 1;
var Block = function(block) {
this.block = document.createElement('div');
this.block.className = 'block';
this.block.id = "block"+id++;
document.body.appendChild(this.block);
}
Block.prototype.coordinates = function(top,left) {
this.block.style.top = top + 'px';
this.block.style.left = left + 'px';
}
Block.prototype.size = function(width,height) {
this.block.style.width = width + 'px';
this.block.style.height = height + 'px';
}
function randomTop() {
var i = Math.random();
var y = (i * (cHeight - 0 + 1)) +0;
var x = Math.floor(y);
return x;
}
function randomLeft() {
var i = Math.random();
var y = (i * (cWidth - 0 + 1)) + 0;
var x = Math.floor(y)
return x;
}
function repeatBlocks() {
block1 = new Block();
block1.size(150,150);
block1.coordinates(randomTop(),randomLeft());
}
setInterval(repeatBlocks,1000);