javascript - 如何在 Chrome 中设置没有自动前缀主机的背景图像 url?

标签 javascript css

假设 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/

相关文章:

javascript - 如何使用express/mongoose和客户端JS将HTML类发布到mongoDB集合中?

javascript - 在 JavaScript 中转义的北欧字符

javascript - 如何在 Angular JS 的弹出窗口外单击时隐藏 uib-popover?

javascript - 按钮不会在 IE 9 中回发

css - SASS 的 grunt-task 允许选项来强制执行代码样式

html - 表格内容超出 div 范围

html - 禁止在 iframe 中滚动

JavaScript 不会与 html 代码交互

javascript - 遍历所有html元素并修改内容

css - flexbox 中元素之间的行分隔符