所以我创建了一个图像标签,但我也希望能够为通过下面的 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/