Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/467.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在框中随机创建图片_Javascript_Html - Fatal编程技术网

Javascript 如何在框中随机创建图片

Javascript 如何在框中随机创建图片,javascript,html,Javascript,Html,我试图从我在一个框中的选择中随机生成一张图片。到目前为止,我已将此代码设置为鼠标单击: function randomize(){ var imgDestination = document.getElementById("stage"); var imgAdded = imageRandomizer(); imgDestination.appendChild(imgAdded); ImgRandomPosition(img

我试图从我在一个框中的选择中随机生成一张图片。到目前为止,我已将此代码设置为鼠标单击:

    function randomize(){
        var imgDestination = document.getElementById("stage");
        var imgAdded = imageRandomizer();
        imgDestination.appendChild(imgAdded);
        ImgRandomPosition(imgAdded);
    }

    function ImgRandomPosition(imgAdded){
        var left = Math.floor((Math.random() * 700) + 1)+"px";
        var top = Math.floor((Math.random() * 500) + 1)+"px";
        var imagestyle = imgAdded.style;
        imagestyle.position = "absolute";
        imagestyle.top = top;
        imagestyle.left = left;
    }

    function imageRandomizer(imgArray, path) {
        path = 'img/';
        var num = Math.floor(Math.random() * imgArray.length);
        var img = imgArray[num];
        var imgStr = '<img src="' + path + img + '" alt = "">';
        document.write(imgStr);
        document.close();
    }
我不知道如何让孩子工作。你知道我该怎么解决这个问题吗, 任何帮助都将不胜感激。 谢谢。

由于imageRandomizer不返回任何内容,因此随机化函数中的var imgAdded=imageRandomizer行没有任何意义,因为imgAdded始终是未定义的

解决方法是在imageRandomizer函数中创建图像元素并设置其src和alt属性,而不是创建图像的HTML并尝试使用Document.write解析它

代码:


你有什么问题?真不敢相信我忘了把它包括在内,我道歉。我相信appendchild可能不被允许,因为我有var imgAdded=imageranodmizer。你知道我该怎么解决这个问题吗?我试过了,但我一直被告知src是一个未使用的变量。你知道为什么会这样吗?再次感谢您的帮助。我对代码做了一些编辑。再试试@tA。
function imageRandomizer(imgArray, path) {
  var
    /* Generate a random index from the array. */
    random = Math.floor(Math.random() * imgArray.length),

    /* Cache the src string saved at the random index. */
    src = imgArray[random],

    /* Create a new image element. */
    image = new Image();

  /* Set a default value to path, if a falsey value is given. */
  path = path || 'img/';

  /* Set the 'src' and 'alt' properties of the image. */
  image.src = path + src;
  image.alt = "";

  /* Return the created image. */
  return image;
}