假设 index.html
url 是 http://localhost/index.html
。
HTML:
<div id='test'></div>
<script>
var el = document.querySelector('#test');
el.style.background = 'url("/test.png")';
</script>
输出 html 将是:
<div id="test" style="background: url(http://localhost/test.png);"></div>
我不想使用主机前缀 http://localhost
。如何防止浏览器的默认行为?
为什么有这个要求?我正在开发一个页面编辑器。我需要在编辑 html 后将干净的 html 发送回服务器。
我只是想知道是否有一种优雅的方式来实现它。请不要使用正则表达式替换或额外的标签属性解决方案。
最佳答案
尝试添加基本标签......在你的情况下是这样的
<base href="http://localhost" target="_blank">
然后在你的脚本中使用:
el.style.backgroundImage = 'url("test.png")';
站立//localhost/test.png 存在,并记住为 div 提供正确的尺寸!
关于javascript - 如何在 Chrome 中设置没有自动前缀主机的背景图像 url?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24155996/