如何在HTML内联JS中使用三重引号设置background-image的URL
内联JavaScript修改backgroundImage的引号嵌套解决方案
由于JavaScript本身不支持三重引号,针对内联场景的引号嵌套问题,给你三个可行的解决办法:
- 省略CSS url()里的引号(最简便)
CSS规范里,url()的引号是可选的,直接去掉URL两端的引号就能彻底避免嵌套问题:
<div onmouseover='document.getElementById("anotherDiv").style.backgroundImage = "url(https://www.test.com/img/20-test-1.jpg)"'></div>
- 转义嵌套的引号
如果一定要保留URL的引号,对内部冲突的引号加转义符\即可:
<!-- 外层用单引号包裹onmouseover逻辑,内部双引号转义 --> <div onmouseover='document.getElementById("anotherDiv").style.backgroundImage = "url(\"https://www.test.com/img/20-test-1.jpg\")"'></div> <!-- 或者外层用双引号,内部单引号转义 --> <div onmouseover="document.getElementById('anotherDiv').style.backgroundImage = 'url(\'https://www.test.com/img/20-test-1.jpg\')'"></div>
- 使用ES6模板字符串(需浏览器支持)
用反引号`包裹backgroundImage的赋值内容,内部可以自由使用单双引号,无需转义:
<div onmouseover='document.getElementById("anotherDiv").style.backgroundImage = `url("https://www.test.com/img/20-test-1.jpg")`'></div>
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

