javascript 在随机位置定位图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17358084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:00:37  来源:igfitidea点击:

Positioning images in random places

javascriptjquerycssimage

提问by user2484181

I want to position random images in random places of the screen. I tried this:

我想在屏幕的随机位置放置随机图像。我试过这个:

$(document).ready(showLetter);
var imgsArray = ["A1", "C1", "F1", "J1", "K1", "L1", "S1", "?1"];

function generateRandomForArray() {
    var num = Math.floor(Math.random() * 8);
    return num;
}

function generateRandom() {
    var num = Math.floor(Math.random() * 400);
    return num;
}

function showLetter() {
    var letter = imgsArray[generateRandomForArray()];
    $("div").append("<img src='imgs/" + letter + ".png'>");
    var left = generateRandom();
    var top = generateRandom();
    $("div").last().css({"top": top + "px", "left": left + "px"});
}

The images appear on top left of the screen. Once again: I want to position them in random places of the screen. I don't know much about CSS. Any ideas? Thanks in advance!

图像出现在屏幕的左上方。再一次:我想将它们放置在屏幕的随机位置。我对 CSS 了解不多。有任何想法吗?提前致谢!

回答by Vinay

Sounds like positioning issue for me. Try like this, i.e., I added position:absolute

对我来说听起来像是定位问题。像这样尝试,即,我添加了position:absolute

function showLetter() {
    var letter = imgsArray[generateRandomForArray()];
    $("div").append("<img src='GameHTML5/images/" + letter + ".png'>");
    var left = generateRandom();
    var top = generateRandom();
    $("div").last().css({"position":"absolute","top": top + "px", "left": left + "px"});
}

回答by user2484181

function generateRandomForArray(min, max) {
  var num = Math.random() * (max - min) + min;
  return Math.floor(num);
}

//generateRandomForArray(0, 8);
//3
//generateRandomForArray(0, 8);
//0
//generateRandomForArray(0, 8);
//2
//generateRandomForArray(0, 8);
//4
//generateRandomForArray(0, 8);
//5
//generateRandomForArray(0, 8);
//7
//generateRandomForArray(0, 8);
//4