Esiste un modo per enumerare tutti gli URL @ font-face (URL dei caratteri web) di una determinata pagina HTML utilizzando JavaScript o JQuery?Enumera gli URL @ font-face utilizzando Javascript/JQuery
risposta
Sì, supponendo si intenda che si desidera trovare tutte le @ font-facce specificate nel foglio di stile anziché quelle effettivamente utilizzate nel documento HTML stesso.
Dato un foglio di stile ragionevolmente standard che assomiglia a questo:
@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';
}
Poi il seguente codice HTML (con inline Javascript) sarà più o meno fare il trucco:
<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>
Con alcune avvertenze:
In primo luogo, uno dei modi principali per specificare @ font-face si basa sulla specificazione dello src due volte, questa tecnica raccoglierà solo il secondo src.
Non ho provato questo cross-browser ma funziona sul mio browser e apre una finestra di avviso con ogni URL di font.
L'hard coded [0] fa guardare solo il primo foglio di stile (in questo esempio ce n'è solo uno). È ragionevolmente banale scrivere un altro ciclo per eseguire il loop su tutti i fogli di stile, se necessario, ma sembra eccessivo per questo esempio.
No, non proprio. Sembra esserci solo questa tecnica: http://paulirish.com/2009/font-face-feature-detection/ per rilevare se è possibile utilizzare @font-face
, ma non per rilevare quali caratteri sono in uso. A parte l'analisi di tutto il codice CSS lato server (o almeno lato server assistito) non c'è modo di fare quello che vuoi, non solo con JS e jQuery. Mi dispiace per quello
Questo è qualcosa che ho appena scritto per uso personale, funziona bene con Chrome, non ho testato con altri browser - ma mi sembra abbastanza normale.
Richiede jquery e identifica tutti i tipi di carattere in uso e le relative origini (se i caratteri Web).
Nota: non gestisce in modo adeguato le variazioni su un font (diversa versione "bold") e non può gestire stili con più font definiti (ad es. Font-family: fonta, fontb, fontc).
jQuery.fn.elementText = function() {
return $(this)
.clone()
.children()
.remove()
.end()
.text()
.replace(/^\s\s*/, '').replace(/\s\s*$/, '')
;
};
Font = function(family, src) {
// In order to properly categorise complex font setups, weight and style need to be
// considered as part of a unique font. (TODO)
this.family = family;
this.src = src;
this.weight = null;
this.style = null;
};
Font.prototype.toString = function() {
return '[Font ' + this.family + ': ' + this.src + ']';
};
var fontNames = {};
var fontObjects = [];
$(':visible').each(function (k, v) {
var $v = $(v);
var font;
if ($v.elementText().length) {
font = $v.css('font-family');
// TODO: seperate by comma, remove quotes
fontNames[font] = font;
}
});
for (var sheet=0; sheet < document.styleSheets.length; sheet++)
for (var i=0; i<document.styleSheets[sheet].cssRules.length; i++)
{
var rule = document.styleSheets[sheet].cssRules[i];
if (rule instanceof CSSFontFaceRule) {
if (fontNames[rule.style.fontFamily])
fontObjects.push(
new Font(rule.style.fontFamily, rule.style.src));
}
}
fontObjects.forEach(function(v) { console.log(v.toString()); });
Esempio di output (qui potete vedere un esempio di ciò che accade quando si hanno diversi 'bold', definisce 'italic' ecc font-style):
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-BookItalic.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Book.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-MediumItalic.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Medium.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-BoldItalic.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Bold.otf)]
[Font 'ITC Legacy Sans Std': url(http://localhost/~admin/tmp/fonts/LegacySansStd-Ultra.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-LightIta.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Light.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Book.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-SemiboldIta.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Semibold.otf)]
[Font 'Ocean Sans Std': url(http://localhost/~admin/tmp/fonts/OceanSansStd-Bold.otf)]
- 1. Enumera tutti gli ordini parziali
- 2. Uso @fontface Carica tipi di carattere corsivo
- 3. C#: Enumera gli indirizzi IP in un intervallo
- 4. Enumera tutti gli elementi in associazioni Selenium Python per Appium
- 5. Enumera i metodi dell'oggetto COM (IDispatch) utilizzando ATL?
- 6. Come reindirizzare gli URL non www a www utilizzando htaccess?
- 7. Selezionare gli elementi con attributo data-url utilizzando HtmlAgilityPack
- 8. Android 4.0.4 MediaPlayer prepara il problema utilizzando gli URL RTSP
- 9. Enumera i valori impostati possibili in Delphi
- 10. Enumera le espressioni regolari tramite UglifyJS
- 11. LINQ Skip enumera ancora elementi ignorati
- 12. Enumera gli spazi dei nomi registrati di un oggetto DOMDocument PHP
- 13. : URL simile utilizzando JavaScript
- 14. gli URL prefisso applicazione Rails
- 15. Riscrivendo gli URL in ASP.NET?
- 16. .htaccess reindirizzare gli URL danneggiati
- 17. Enumera le chiavi in un dizionario?
- 18. Git enumera lentamente file non tracciati inesistenti
- 19. Enumera su un enum in C++
- 20. Enumera le sottochiavi del registro in delphi
- 21. sostituire gli URL nel testo con collegamenti agli URL
- 22. Django nominati gli URL non riconosciuti dal template tag url
- 23. Sistema URL breve: come reindirizzare gli URL personalizzati?
- 24. Tela drawImage utilizzando URL dati
- 25. URL Django, utilizzando un? nell'URL
- 26. Ottieni gli URL amichevoli in Liferay
- 27. Estrai URL da una stringa utilizzando PHP
- 28. HTTPS URL utilizzando il WebDownloadClient genera un'eccezione
- 29. Emettere un URL di repository utilizzando Octokit.rb
- 30. utilizzando wget, ma ignorare parametri URL
Forse è evidente a voi, ma Voglio menzionare un problema di questa e [la soluzione di Orwellophile] (http://stackoverflow.com/a/19343013/2590616). Funzionerà solo sullo stesso foglio di stile del dominio. Se provi a leggere le regole di un foglio di stile su un dominio diverso, ad es. su un cdn, si imbocca una norma interdominio in Chrome e si ottiene un errore di script ("SecurityError: l'operazione non è sicura.") in Firefox. – RiZKiT