我正在创建一个 Javascript 小部件,它使用 Angular 和 NVD3 库来显示某些图形。在包含用于生成这些图形的代码的脚本文件(位于服务器中)中,除了 NVD3 使用的 CSS 文件(nv.d3.css)之外,我还添加了用于动态添加指向这些库的脚本文件的代码正确呈现其元素:
loadScript('http://localhost:3000/javascript/bower_components/angular/angular.js');
loadScript('http://localhost:3000/javascript/bower_components/d3/d3.js');
loadScript('http://localhost:3000/javascript/bower_components/nvd3/build/nv.d3.js');
loadScript('http://localhost:3000/javascript/bower_components/angular-nvd3/dist/angular-nvd3.js');
var css = document.createElement('style');
css.type = 'text/css';
css.setAttribute('src', 'http://localhost:3000/javascript/bower_components/nvd3/build/nv.d3.css');
$("body").append(css);
function loadScript(address){
var angularnvd3Script = document.createElement('script');
angularnvd3Script.setAttribute('type', 'text/javascript');
angularnvd3Script.setAttribute('src', address);
$("body").append(angularnvd3Script);
}
当嵌入小部件的客户端应用程序运行时,脚本加载成功,图表从数据的 Angular 正确显示,CSS 文件似乎也正确添加到客户端 HTML 文件中,但未使用,因为图表的样式没有被拾取。我试图将文件添加到头部而不是正文中,但发生了同样的意外行为。 有谁知道问题出在哪里?提前致谢
最佳答案
好吧,您正在混合使用两种方法将 CSS 添加到您的页面。您可以使用 style
标签或 link
标签。
通过使用 style
标签你不能使用 href
所以在你的情况下你必须使用 link
方法:
var link = document.createElement('link')
link.setAttribute('rel', 'stylesheet')
link.setAttribute('type', 'text/css')
link.setAttribute('href', 'http://localhost:3000/javascript/bower_components/nvd3/build/nv.d3.css')
document.getElementsByTagName('head')[0].appendChild(link)
关于javascript - 未加载动态添加的 CSS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37807110/