Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/431.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_Image_Attributes - Fatal编程技术网

创建图像元素,然后通过javascript错误设置样式属性

创建图像元素,然后通过javascript错误设置样式属性,javascript,html,image,attributes,Javascript,Html,Image,Attributes,因此,我创建了一个图像标记,但我也希望能够为通过下面的javascript创建的图像标记设置属性 function start() { imageTag = document.createElement("IMG"); //Creates image tag w = window.innerWidth //finds width of web page h = window.innerHeight //fin

因此,我创建了一个图像标记,但我也希望能够为通过下面的javascript创建的图像标记设置属性

function start()
        {
            imageTag = document.createElement("IMG"); //Creates image tag
            w = window.innerWidth //finds width of web page
            h = window.innerHeight //finds height of web page
            pic = document.getElementsByTagName("img"); //finds the tag name of "img"
            x = Math.floor(Math.random()*(w))+1; //finds a random width that can be used for x coordinate that fits within site
            y = Math.floor(Math.random()*(h))+1; //finds a random height that can be used for y coordinate that fits within site
            pic.style.left = x+"px"; //Sets the style attribute that will be in the image tag that was created earlier *ERROR*
            pic.style.top = y+"px"; //Sets the style attribute that will be in the image tag that was created earlier *ERROR*
            imageTag.setAttribute("src", "popo.jpg" ); //sets the image tags source
            document.body.appendChild(imageTag);
        }

我似乎不明白为什么left和top的style属性没有像创建的图像标记中的另一个picture source属性那样添加。如果html中已经有一个图像标记,那么它可以工作,但当我用javascript创建一个图像标记时它就不能工作了,所以这没有意义,因为我觉得它应该可以工作。

听起来你会受益于保留对上次创建的图像的引用,这样你就可以轻松设置位置属性

比如说

var prevImage;

function start() {
    if (prevImage) {
        var x = Math.floor(Math.random() * window.innerWidth) + 1,
            y = Math.floor(Math.random() * window.innerHeight) + 1;            

        prevImage.style.left = x + 'px';
        prevImage.style.top = y + 'px';
    }
    var img = document.createElement('img');
    img.src = 'popo.jpg';
    document.body.appendChild(img);
    prevImage = img;
}

返回一个集合,而不是单个元素,并且仅返回您试图设置新创建的图像或先前添加的图像元素的左侧和顶部的文档中已包含的元素