使用JavaScript添加img属性

时间:2016-09-01 19:26:34

标签: javascript html appendchild setattribute createelement

我知道这个问题已被多次询问,但当我尝试appendChild imgdiv时,我遇到了问题。 这是代码:



var picture = document.createElement("img");
 picture.id= "xmark";
picture.src= "x.png";
picture.setAttribute("position","absolute");						 
picture.setAttribute("bottom", 100 + 'px'); 
picture.setAttribute("left",500 + 'px');
//I also tried
picture.style.bottom= 100 + 'px'; 
picture.style.left = 100 + 'px';  
// I even tried this, but returns "cannot read property style of null" error
document.getElementById("xmark").style.bottom=100+"px";

document.getElementById("divmax").appendChild(picture);	

<div id="divmax"></div>
&#13;
&#13;
&#13;

是的,jpg文件保存正确。我查了一下。

1 个答案:

答案 0 :(得分:0)

这是有效的,只需更改您的position媒体资源,就像您尝试的其他方式一样:

&#13;
&#13;
var picture = document.createElement("img");
picture.id= "xmark";
picture.src= "https://placehold.it/250x250";
picture.style.position = 'absolute';
picture.style.bottom = 100 + 'px'; 
picture.style.left = 100 + 'px';  

document.getElementById("divmax").appendChild(picture);	
&#13;
<div id="divmax"></div>
&#13;
&#13;
&#13;