用div背景元素替换所有图像

时间:2010-11-03 05:14:51

标签: javascript html css dom

var all = document.getElementsByTagName( 'img' );
for( i = 0; i < all.length; i++ ){
    var newimg;
    (newimg=document.createElement('div')).style.cssText="display:inline;width:"+all[i].width+"px;height:"+all[i].width+"px;background-image:url("+all[i].src+");";
    all[i].parentNode.replaceChild( newimg, all[i] );
}

仅替换4个示例图像中的两个图像(1和3)(test1.jpg到test4.jpg),也不显示任何div背景。 我做错了吗?

到目前为止生成的输出结果:

<div style="display: inline; width: 400px; height: 400px; background-image: url(&quot;http://localhost/test1.jpg&quot;);"></div> 
<img src="test2.jpg">
<div style="display: inline; width: 796px; height: 796px; background-image: url(&quot;http://localhost/test3.jpg&quot;);"></div> 
<img src="test4.jpg">

谢谢!

1 个答案:

答案 0 :(得分:2)

View live demo

你必须反向循环迭代。由于每次更换img时,所有数组的长度减1。因此,您无法访问所有[1],所有[3]元素。

同样由于display:inline,其他css文字(高度/宽度/背景/)图片不适用于您的div,因此请将其删除并改为使用float:left

希望这会有所帮助。

相关问题