我正在将 Bootstrap 用于我正在编写的 chrome 扩展。当作为内容脚本导入时,css 似乎与我正在查看的许多网站发生冲突(即使在谷歌搜索结果页面中)。
想知道我是否可以做些什么来将其范围仅限于我使用内容脚本注入(inject)的 dom 元素?
最佳答案
解决方法是使用 <style scoped>
.
本质上,它允许您将样式应用于 DOM 节点及其子节点,但不是它的父节点 . CSS-Tricks 上有一篇不错的文章解释如何使用它。
问题是它没有得到很好的支持,即使在 Chrome 中也是如此,所以你必须使用 jQuery polyfill。这基本上是一个 jQuery 插件,可以模拟您期望 <style scoped>
提供的功能。 .
这是一个有效的JSFiddle使用 Bootstrap 就可以做到这一点。
这是一个如何在扩展中实现它的示例:
content_script.js :
$.scoped(); // Initialize the plugin
...
bootstrapped = document.createElement("div");
bootstrapped.innerHTML = "<style scoped>";
bootstrapped.innerHTML += "@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');";
bootstrapped.innerHTML += "</style>";
document.body.appendChild(bootstrapped);
...
document.body.appendChild(myDOM); // Will not possess Bootstrap styles
bootstrapped.appendChild(myDOM); // Will possess Bootstrap styles
现在,请确保在您的页面中包含 jQuery 以及 Scoped Plugin:
"content_scripts": [ {
"js": [ "jquery.min.js", "jquery.scoped.min.js", "content_script.js" ],
"matches": [ "http://*" ]
}]
关于google-chrome - 在 chrome 扩展中,twitter bootstrap css 发生冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13123044/