2010-04-30 61 views
2

我使用JavaScript來創建像這樣的圖像元素:加入IMG在JS

var img = document.createElement('img'); 

我會怎麼做給這個的IMG 100%的寬度?

+2

不使用jQuery的獎勵積分 – 2010-04-30 17:23:53

回答

5

....

var img = document.createElement('img'); 
img.setAttribute('width', '100%'); 

請確保您連接的imgbody

document.getElementsByTagName('body')[0].appendChild(img); 
3

您既可以指定圖像的寬度:(從別人的回答)

var img = document.createElement('img'); 
img.setAttribute('width', '100%'); 
document.getElementsByTagName("body")[0].appendChild(img); 

,或者指定一個類名和CSS的目標是:

的JavaScript:

var img = document.createElement('img'); 
img.setAttribute('class', 'wide'); 
document.getElementsByTagName("body")[0].appendChild(img); 

CSS:

img.wide { 
    width:100%; 
}