【问题标题】:Add img attributes using JavaScript使用 JavaScript 添加 img 属性
【发布时间】:2017-01-09 19:19:27
【问题描述】:

我知道这个问题已经被问过好几次了,但是当我尝试appendChildimgdiv 时遇到问题。 这是代码:

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>

是的,jpg 文件已正确保存。我查过了。

【问题讨论】:

  • 有什么问题?
  • 当然,试图在文档中查找图片会失败——您只能在查找之后添加它。如果你交换最后两行 JS 行,它可以工作。
  • 问题是什么都没有发生。样式不会因我的归属而改变
  • picture.style.position 这样添加别人

标签: javascript html appendchild setattribute createelement


【解决方案1】:

这行得通,只需更改您的 position 属性,就像您尝试的其他方式一样:

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);	
<div id="divmax"></div>

【讨论】:

    猜你喜欢
    • 2022-08-03
    • 2021-11-29
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 2011-09-12
    • 2016-03-31
    • 1970-01-01
    相关资源
    最近更新 更多