【问题标题】:twitter bootstrap css clashes while in chrome extensions在 chrome 扩展中,twitter bootstrap css 发生冲突
【发布时间】:2013-01-01 01:48:39
【问题描述】:

我正在为我正在编写的 chrome 扩展程序使用引导程序。当作为内容脚本导入时,css 似乎与我正在查看的许多网站(甚至在谷歌搜索结果页面中)发生冲突。

想知道我是否可以做些什么来将其范围仅限于我使用内容脚本注入的 dom 元素?

【问题讨论】:

    标签: google-chrome google-chrome-extension twitter-bootstrap


    【解决方案1】:

    解决方法是使用<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://*" ]
    }]
    

    【讨论】:

    • &lt;style scoped&gt; 规范here。 Scoped 插件可用here
    • 如果你不使用 jQuery 怎么办? vanilla JS有什么办法吗?
    猜你喜欢
    • 2012-04-28
    • 2016-04-03
    • 2016-02-12
    • 1970-01-01
    • 2011-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多