我想在 div 中定位追加图像。图像应在 500 的高度和 500 的宽度内显示 5 次。它们应该随机放置在不同的位置,但它们不应跨越 div 的高度和宽度。但是我的代码产生的结果是图像始终位于从右到左的倾斜线上,并且始终创建在一起的面孔。
这是我的代码:
var theLeftSide = document.getElementById("leftSide");
var top_position = Math.random() * 500 - 100;
var left_position = Math.random() * 500 - 100;
numberOfFaces = 5;
function generateFaces() {
for (var i = 0; i < 6; i++) {
createElement(i);
numberOfFaces += numberOfFaces;
}
}
function createElement() {
var image = document.createElement('img');
image.src = "smile.png";
image.style.position = 'absolute';
image.style.top = top_position + "px";
image.style.left = left_position + "px";
theLeftSide.appendChild(image);
top_position += 20;
left_position += 20;
}
最佳答案
图像被放置在一条对 Angular 线中,因为您每次调用都将 top_position
和 left_position
递增 20。基本上你选择一个随机开始,例如10, 15
,代表笑脸。然后笑脸 2 被放置在 30、45
,笑脸 3 被放置在 50、65
,等等。要解决这个问题,您需要为每个图像重新生成两个位置。
下面的代码会做你想做的。我从 MDN ( here ) 添加了 getRandomInt 以使其更容易获得你想要的数字。
var theLeftSide = document.getElementById("leftSide");
var top_position;
var left_position;
numberOfFaces = 5;
function generateFaces() {
for (var i = 0; i < 6; i++) {
top_position = getRandomInt(0, 500);
left_position = getRandomInt(0, 500);
createElement(i);
numberOfFaces += numberOfFaces;
}
}
function createElement() {
var image = document.createElement('img');
image.src = "smile.png";
image.style.position = 'absolute';
image.style.top = top_position + "px";
image.style.left = left_position + "px";
theLeftSide.appendChild(image);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
请记住,这不符合 div 的边界。为此,您必须将 div 的 position
设置为 relative
,设置宽度和高度,并更新此代码以获取 div 尺寸(例如,使用答案 here ).图像应基于其左上角定位,因此您还需要从用于生成随机位置编号的宽度和高度中减去图像的宽度和高度,以防止图像在底部或右侧溢出。
关于javascript - 如何通过javascript在随机位置但在特定宽度和高度内附加div来定位一张图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34360592/