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

标签 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 //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 属性没有像创建的图像标签中的其他图片源属性一样添加。如果我在 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;
}

关于javascript - 创建图像元素然后通过javascript错误设置样式属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30430666/

相关文章:

javascript - 委托(delegate)的 'on' 处理程序中是否有对所选元素的引用?

javascript - 带复选框的点击

JQuery 如果跨度值 = 0 改变颜色

允许图像双线性变换的Java库

image - 使用 OpenCV 将 12 位 Bayer 图像转换为 8 位 RGB

javascript - 使用javascript检查服务器上是否存在带有韩文字符的文件?

javascript - 无法抓取 ally.com

wordpress - 图像媒体正在创建 768px 的新图像大小,但如何阻止它?

javascript - 没有 stretch img child 的 CSS ScaleY

javascript - 即时生成 javascript 和 html block