1. 使用document.getElementById()方法获取到每个div元素,并将其存储在变量中;
2. 使用document.createElement()方法创建一个img元素,并将其存储在变量中;
3. 使用img元素的src属性设置图片的路径;
4. 使用appendChild()方法将img元素添加到每个div元素中。
以上就是在javascript中给三个div添加图片的方法,希望能够帮助您解决问题。
有两种比较直接的方式,\x0d\x0a\x0d\x0a第一种方法:预先设置一个样式,然后在js中 *** 作,给div加上这个class。\x0d\x0ahtml代码:\x0d\x0a-----\x0d\x0a\x0d\x0a\x0d\x0a-----\x0d\x0a\x0d\x0a预先设置一个样式:\x0d\x0a-----\x0d\x0a.bg {\x0d\x0a background-image: url(xxx.jpg)\x0d\x0a}\x0d\x0a-----\x0d\x0a\x0d\x0a然后js获取这个div,给div加上名为bg的class\x0d\x0a-----\x0d\x0avar div = document.getElementById('test')\x0d\x0adiv.className += ' bg'\x0d\x0a-----\x0d\x0a\x0d\x0a第二种方法,直接设置div的style属性:\x0d\x0a\x0d\x0a-----\x0d\x0avar div = document.getElementById('test')\x0d\x0adiv.style.backgroundImage = 'url(xxx.xxx)'\x0d\x0a----- 回答于 2022-11-16欢迎分享,转载请注明来源:内存溢出
评论列表(0条)