[英]JQuery: How to get assigned font to element
是否可以在 jQuery 中檢索元素的指定字體?
假設有css:
#element
{
font-family: blahblah,Arial;
}
在上面的例子中,Arial 字體將被分配給#element。 有沒有辦法通過 JS/JQuery 獲取這些信息?
就像是:
$('#element').css('font-family');
只返回blahblah,Arial;
(function($) {
$.fn.detectFont = function() {
var fonts = $(this).css('font-family').split(",");
if ( fonts.length == 1 )
return fonts[0];
var element = $(this);
var detectedFont = null;
fonts.forEach( function( font ) {
var clone = element.clone().css({'visibility': 'hidden', 'font-family': font}).appendTo('body');
if ( element.width() == clone.width() )
detectedFont = font;
clone.remove();
});
return detectedFont;
}
})(jQuery);
編輯:必須從 dom 中刪除克隆的項目。
剛才再提一下,它仍然依賴於元素寬度 - 所以你的里程可能會有所不同。
$('#element').detectFont(); //outputs Arial
您可以使用 Detector 庫來做到這一點: http : //www.lalit.org/lab/javascript-css-font-detect/
當瀏覽器從列表中獲取第一個找到的字體時,您應該查看字體列表並嘗試檢查您的系統中是否有這種字體。
這是 JS/JQuery 代碼:
$(function() {
var detectFont = function(fonts) {
var detective = new Detector(), i;
for (i = 0; i < fonts.length; ++i) {
if (detective.detect(fonts[i]) !== true) {
continue
}
return fonts[i];
}
}
var fonts = $('#abcde').css('font-family');
fonts = fonts.split(',');
console.log(detectFont(fonts));
});
這是現場演示,我已經准備好了: http : //jsfiddle.net/netme/pr7qb/1/
希望,這種方法會對你有所幫助。
修改了 kmfk 的答案,使其適用於所有元素。 塊元素具有固定或動態寬度將不起作用,因此它使用內聯元素:
/**
* Detects the font of an element from the font-family css attribute by comparing the font widths on the element
* @link http://stackoverflow.com/questions/15664759/jquery-how-to-get-assigned-font-to-element
*/
(function($) {
$.fn.detectFont = function() {
var fontfamily = $(this).css('font-family');
var fonts = fontfamily.split(',');
if ( fonts.length == 1 )
return fonts[0];
var element = $(this);
var detectedFont = null;
fonts.forEach( function( font ) {
var clone = $('<span>wwwwwwwwwwwwwwwlllllllliiiiii</span>').css({'font-family': fontfamily, 'font-size':'70px', 'display':'inline', 'visibility':'hidden'}).appendTo('body');
var dummy = $('<span>wwwwwwwwwwwwwwwlllllllliiiiii</span>').css({'font-family': font, 'font-size':'70px', 'display':'inline', 'visibility':'hidden'}).appendTo('body');
//console.log(clone, dummy, fonts, font, clone.width(), dummy.width());
if ( clone.width() == dummy.width() )
detectedFont = font;
clone.remove();
dummy.remove();
});
return detectedFont;
}
})(jQuery);
$('#element').css("font-family", "Arial");
試試這個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.