我加载任何网页。然后打开 firebug 控制台并运行下面的 javascript,这会在页面的头部创建一个链接元素。代码如下。
var s = document.createElement('link');
s.setAttribute('href', 'file:///home/simha/.public_html/new1.css');
s.setAttribute('rel', 'stylesheet');
s.setAttribute('type', 'text/css');
document.getElementsByTagName('head')[0].appendChild(s);
alert('Stylesheet injected!');
文件内容:///home/simha/.public_html/new1.css
body { 背景色:#0000ee !important; }
我在 firebug 控制台中运行代码,以下内容出现在 html 的头部
<link type="text/css" rel="stylesheet" href="file:///home/simha/.public_html/new1.css">
但是body的背景颜色没有变化(变成蓝色)。
我独立于在 firebug 中编辑 css 检查了 css 规则,背景颜色变为蓝色。
我安装了 apache 网络服务器。所以我也尝试将“file:///home/simha/.public_html/new1.css”改为“localhost/~simha/new1.css”,但它仍然不起作用。
我使用的是 firefox 浏览器。
最佳答案
这是因为出于安全原因,仅当文档也已从本地 URI 加载时,才能从本地 URI 方案(如 file:
)加载外部资源。
关于javascript - css 样式表没有被添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20815989/