You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过JavaScript将一个div的背景图复制到另一个div?

解决背景图赋值失败的问题
  • 问题根源:element.style只能读取元素的内联样式(直接写在元素style属性里的样式),如果你的imgHouse的背景图是通过CSS类、外部样式表设置的,imgHouse.style.backgroundImage会返回空字符串,自然赋值给houseImg也没用。
  • 正确做法:用window.getComputedStyle()获取元素最终渲染的计算样式,再赋值给目标元素。

代码示例:

// 获取两个DOM元素
const imgHouse = document.querySelector('.imgHouse');
const houseImg = document.querySelector('.houseImg');

// 获取imgHouse最终渲染的背景图样式
const targetBg = window.getComputedStyle(imgHouse).backgroundImage;

// 把背景图赋值给houseImg
houseImg.style.backgroundImage = targetBg;

这样不管背景图是通过内联、CSS类还是外部样式表设置的,都能正确获取到最终生效的背景图值,完成赋值。

内容的提问来源于stack exchange,提问作者Tojiddin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 23:29:54