使用JS,是否可以在加载时返回页面中包含的所有CSS样式表的列表

Using JS, is it possible to return a list of all CSS stylesheets included in a page, when it loads?

本文关键字:包含 CSS 列表 样式 是否 JS 返回 加载 使用      更新时间:2023-09-26

使用jQuery或纯JavaScript,我可以在页面初始加载时返回页面中包含的每个样式表的列表吗?

我所要做的就是将样式表名称列表打印到控制台中,不需要关于样式表的其他信息。

如果我是正确的,那么Names是指每个样式表的文件名。

考虑这个例子:

jQuery("link[href*='.css']").each(function(){
    console.log(jQuery(this).attr('href').split('/').pop());
});

在这里,我使用这个link[href*='.css']选择器来选择所有(包括不活动的)样式表。

如果使用jQuery:

console.log($('link[rel=stylesheet]'));

如果您使用的是jQuery,您可以执行以下操作:

$(document).ready(function() {
    console.log($("link[rel='stylesheet']").attr("href"));
});

https://jsfiddle.net/vzfhjg16/

这段代码收集stylesheet上具有rel属性的所有link,然后对它们进行迭代并记录它们的属性href。您可以使用循环中的行在任何您想要的地方显示样式表名称

$("head link[rel='stylesheet']").each(function (){
    console.log($(this).attr("href"));
});

工作示例

试试这个,

var styles = document.styleSheets;
$(styles).each(function(index,value){
    console.log(value.href==null ? null : value.href.split('/').pop())
});
var styleSheetList = document.styleSheets;

参考:https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets