将元素放置在随机位置
问题描述:
我试图用这段代码将元素放置在随机位置,但它只是将元素放置在我的容器元素的顶部。我究竟做错了什么?将元素放置在随机位置
create: function(){
console.log("cone created");
var el = document.createElement('div');
el.classList.add('cone');
this.container.appendChild(el);
this.el = el;
this.x = Math.random() * canvas.innerWidth + 'px';
this.y = Math.random() * canvas.innerHeight + 'px';
},
答
也许插入div
与内联的CSS可以处理这个。
我写了一个例子:
$(document).ready(function() {
var sqrPixel = 10;
var posX = 30;
var posY = 100;
$('body').append('<div style="background: #ccc; box-shadow: 2px 2px 2px #000; position: absolute; width: ' + sqrPixel + 'px; height: ' + sqrPixel + 'px; left: ' + posX + '; top: ' + posY + ';"></div>');
});
我的平方追加到body
。如果你想改变它。您可以随机设置posX
和posY
。
我知道它看起来有点混乱,但至少它对我有用。
答
我假设“帆布”不是真的帆布,它只是一个<div>
。
在这种情况下,你需要做的几件事情:
- 确保您的容器具有
position:relative
- 确保你的容器的孩子有
position:absolute
- 添加
el.style.left = this.x; el.style.top = this.y;
实际位置的元素
实际上用'this.x'和'this.y'做些什么的代码在哪里? –