任何将js-ref和css-ref包含为单个ref的方法



您知道是否有一种方法可以将js-ref和css-ref作为单个ref包含在html中吗?通常,这些引用被单独包含在html头中,但我的经理想知道是否有一种简化的方法可以让下游消费者将这些引用添加为单个引用。

一种可能的方法是只包含JavaScript,并在其中加载CSS。

看看这里:如何使用Javascript加载CSS文件?

您可以将CSS作为字符串包含在JavaScript:中

var myStylesheet = 
  'body { background-color: blue; }
   #my-div{ background-color: white; }'
  ;

然后:

var styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.innerHTML = myStylesheet;
document.head.appendChild(styleElement);

这将创建一个样式元素并将其放置在文档头中。

相当于:

<head>
  ...
  <style type="text/css">
    body { background-color: blue; }
    #myDiv { background-color: white; }
  </style>
</head>

这是例如dat.gui库所使用的绑定方法;例如,请参阅未缩小版本第42行定义的inject函数,以及第2857行的(非常长!)样式字符串。

最新更新