sac*_*haa 5 javascript jquery font-face
有没有办法使用JavaScript或JQuery枚举给定HTML页面的所有@ font-face URL(Web字体URL)?
是的,假设您想要查找样式表中指定的所有 @font-faces,而不是 HTML 文档本身中实际使用的 @font-faces。
给定一个相当标准的样式表,如下所示:
@font-face {
font-family: 'Lobster12Regular';
src: url('fonts/lobster_1.2-webfont.eot');
src: url('fonts/lobster_1.2-webfont.eot?#iefix') format('embedded-opentype'),
url('fonts/lobster_1.2-webfont.woff') format('woff'),
url('fonts/lobster_1.2-webfont.ttf') format('truetype'),
url('fonts/lobster_1.2-webfont.svg#Lobster12Regular') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'AllerRegular';
src: url('fonts/aller_std_rg-webfont.eot');
src: url('fonts/aller_std_rg-webfont.eot?#iefix') format('embedded-opentype'),
url('fonts/aller_std_rg-webfont.woff') format('woff'),
url('fonts/aller_std_rg-webfont.ttf') format('truetype'),
url('fonts/aller_std_rg-webfont.svg#AllerRegular') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'AllerBold';
src: url('fonts/aller_std_bd-webfont.eot');
src: url('fonts/aller_std_bd-webfont.eot?#iefix') format('embedded-opentype'),
url('fonts/aller_std_bd-webfont.woff') format('woff'),
url('fonts/aller_std_bd-webfont.ttf') format('truetype'),
url('fonts/aller_std_bd-webfont.svg#AllerBold') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'AllerLight';
src: url('fonts/aller_std_lt-webfont.eot');
src: url('fonts/aller_std_lt-webfont.eot?#iefix') format('embedded-opentype'),
url('fonts/aller_std_lt-webfont.woff') format('woff'),
url('fonts/aller_std_lt-webfont.ttf') format('truetype'),
url('fonts/aller_std_lt-webfont.svg#AllerLight') format('svg');
font-weight: normal;
font-style: normal;
}
h1 {
font-family: 'Lobster12Regular';
}
h2 {
font-family: 'AllerRegular';
}
Run Code Online (Sandbox Code Playgroud)
那么下面的 HTML(带有内联的 Javascript)或多或少就能达到目的:
<html>
<head>
<link rel="stylesheet" href="test.css">
</head>
<body>
<h1>Hello</h1>
<h2>Hello</h2>
<script type="text/javascript">
var pattern=/url\(.*?\)/g;
for (var i=0;i<document.styleSheets[0].cssRules.length;i++)
{
var urls=document.styleSheets[0].cssRules[i].cssText.match(pattern);
if (urls)
{
for (var j=0;j<urls.length;j++)
{
alert(urls[j]);
}
}
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
有一些警告:
首先,指定 @font-face 的主要方法之一依赖于指定 src 两次,这种技术只会选取第二个 src。
我还没有测试过这个跨浏览器,但它可以在我的浏览器上运行,并弹出一个带有每个字体网址的警告框。
硬编码的 [0] 使其仅查看第一个样式表(在本例中只有一个)。如果需要的话,编写另一个循环来遍历所有样式表是相当简单的,但对于这个例子来说似乎有点过分了。
| 归档时间: |
|
| 查看次数: |
2546 次 |
| 最近记录: |