javascript 获取系统字体

============================================仅可用与IE================================================
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> 获取当前系统字体和排版样式www.aa25.cn </TITLE>

<SCRIPT LANGUAGE="JavaScript">
<!--
function getSystemFonts(){
    var a=dlgHelper.fonts.count;
    var fArray = new Array();
    var oDropDown = document.all.fonts;
    for (i = 1;i < dlgHelper.fonts.count;i++){
        fArray[i] = dlgHelper.fonts(i);
        var aOptions = oDropDown.options;    
        var oOption = document.createElement("OPTION");
        aOptions.add(oOption);    
        oOption.text = fArray[i];
        oOption.Value = i;
    }
}

function getBlockFormats(){
    var a=dlgHelper.blockFormats.count;
    var fArray = new Array();
    var oDropDown = document.all.formats;
    oDropDown.setAttribute("id","FormatList");
    for (i = 1;i < dlgHelper.blockFormats.count;i++)
    {
        fArray[i] = dlgHelper.blockFormats(i);
        var aOptions = oDropDown.options;    
        var oOption = document.createElement("OPTION");
        aOptions.add(oOption);    
        oOption.text = fArray[i];
        oOption.Value = i;
    }
}
//-->
</SCRIPT>
</HEAD>

<BODY οnlοad="getSystemFonts();getBlockFormats()">
系统字体和排版样式 SystemFont and BlockFormats__www.aa25.cn<BR>
<Select NAME="fonts" οnchange="document.body.style.fontFamily = this.options[this.selectedIndex].text">
</Select>
<Select NAME="formats" οnchange="document.body.style.fontFamily = this.options[this.selectedIndex].text">
</Select>
<OBJECT ID=dlgHelper CLASSID="clsid:3050f819-98b5-11cf-bb82-00aa00bdce0b" WIDTH="0px" HEIGHT="0px"></OBJECT>
</BODY>

</HTML>


以下代码在IE下测试有效,如果你想看效果可复制以下代码另存为 "系统字体.html "  的静态文件。

以下为引用的内容:
<html>
<head>
</head>
<body>
<DIV style="LEFT: 0px; POSITION: absolute; TOP: 0px">
<OBJECT ID="dlgHelper" CLASSID="clsid:3050f819-98b5-11cf-bb82-00aa00bdce0b" WIDTH="0px" HEIGHT="0px"></OBJECT>
<script language="javascript" type="text/javascript">
// FontFacesMenu.js
var fontsArray = new Array();
var fontsIsAdded = false;
function fontFacesMenuEnter(fontFacesDropdownList, dlgHelperId)
{
 if((fontsIsAdded == false )||(fontsArray==''))
 {
  fontsArray = getSystemFonts(dlgHelperId);
 
  fontsIsAdded = true;
  for (var s=1; s < fontsArray.length; s++)
  {
   newOption = document.createElement("option");
   newOption.value = fontsArray[s];
   newOption.text = fontsArray[s];
   fontFacesDropdownList.add(newOption);
  }
 }
}
function getSystemFonts(dlgHelperId)
{
 var a = document.all(dlgHelperId).fonts.count;
 var fArray = new Array();
 for (i = 1;i <= parent.document.all(dlgHelperId).fonts.count;i++){
  fArray[i] = parent.document.all(dlgHelperId).fonts(i);
 }
 return fArray;
}
</script>
</DIV>
<select id="blessingWords_FontFamily_DL" name="blessingWords_FontFamily_DL" style="width:140px;" οnmοuseenter="fontFacesMenuEnter(this, 'dlgHelper');//updateFontList();">
      <option value=""><- 设置字体 -></option>
</select>
</body>

运行效果如图:



下面我们一步一步来做
1.首先在需要获取系统字体的网页<body>后加入以下代码:

以下为引用的内容:
<DIV style="LEFT: 0px; POSITION: absolute; TOP: 0px">
<OBJECT ID="dlgHelper" CLASSID="clsid:3050f819-98b5-11cf-bb82-00aa00bdce0b" WIDTH="0px" HEIGHT="0px">
</OBJECT>
<script src="FontFacesMenu.js" language="javascript" type="text/javascript"></script>
</DIV>

2.将以下内容保存为:FontFacesMenu.js文件。

以下为引用的内容:
// FontFacesMenu.js
var fontsArray = new Array();
var fontsIsAdded = false;
function fontFacesMenuEnter(fontFacesDropdownList, dlgHelperId)
{
 if((fontsIsAdded == false )||(fontsArray==''))
 {
  fontsArray = getSystemFonts(dlgHelperId);
  
  fontsIsAdded = true;
  for (var s=1; s < fontsArray.length; s++)
  {
   newOption = document.createElement("option");
   newOption.value = fontsArray[s];
   newOption.text = fontsArray[s];
   fontFacesDropdownList.add(newOption);
  }
 }
}

function getSystemFonts(dlgHelperId)
{
 var a = document.all(dlgHelperId).fonts.count;
 var fArray = new Array();
 for (i = 1;i <= parent.document.all(dlgHelperId).fonts.count;i++){
  fArray[i] = parent.document.all(dlgHelperId).fonts(i);
 }
 return fArray;
}

3.在网页需要插入字体下拉菜单的位置处插入以下代码:

系统字体:

以下为引用的内容:
<SELECT ID="blessingWords_FontFamily_DL" name="blessingWords_FontFamily_DL" style="width:140px;" οnmοuseenter="fontFacesMenuEnter(this, 'dlgHelper');//updateFontList();">
<OPTION VALUE=""><- 设置字体 -></OPTION>      
</SELECT> 


OK!看到效果了没有?如图:
 
注:如果需要加上选中后的事件,在onChange中改变成你自己的相应事件处理即可。


===========================兼容其他浏览器的方法==================================================================================

JavaScript code to detect available availability of a particular font in a browser using JavaScript and CSS.

Update: I have updated the algo of the script and it is almost 100% accurate.

This JavaScript class can be used to guess if a particular font is present in a machine. This may be help of desktop-like web application developers when they want to provide different skins or fonts preferences to their users. This may also be help for blog skin designers which can provide different fonts for different users based on the list of fonts on their machine. Designers don’t have to rely on the most common fonts like Arial, Verdana or Times New Roman. Since increasing number of users
have modern PC with new operating system / applications, they may very well have a wide array of other common fonts in their machine.

How does it work?

This code works on the simple principle that each character appears differently in different fonts. So different fonts will take different width and height for the same string of characters of same font-size.

Widths of same text in different fonts

We try to create a string with 3 generic font-face, monospace, sans-serif and sans and note their width. Then try to create the same string in HTML using the font to be tested and the generic fallback font. If the font-face is not available, it takes up the generic fallback font-face. We then compare the width of the string with the new font and width of the string with the fallback generic font-face, if they are different, then the font exists, otherwise not.

<span style="font-family: monospace; font-size: 72px">mmmmmmmmmmlli</span>
vs.
<span style="font-family: New-Font, monospace; font-size: 72px">mmmmmmmmmmlli</span>

Since this test is repeated three times against 3 font families, it gives almost 100% accurate results. The string which we will use to generate the widths can be anything. But I guess we use ‘m’ or ‘w’ because these two characters take up the maximum width. And we use a trailing ‘l’ and ‘i’ so that the same width fonts-faces can get separated based on the width of l character. I have tested it on Firefox, IE, Opera, Safari, Chrome

Note:
It required to execute the script after its completely loaded for some browsers like Opera. (Opera cannot calculate theoffsetWidth until all the parents are completely loaded)

Download ver 0.3 (24 Mar 2012)

Released under Apache Software License 2.0.

Plain text JS code (v0.3)

Demo

You can test any Font here:


// Usage
window.onload = function() {
    var detective = new Detector();
    alert(detective.detect('font name'));
};

Fonts on your computer

This table below shows which fonts are present on your system. (I have listed some of the most common and some uncommon fonts.)

Font NameDetected?
cursivefalse
monospacetrue
seriftrue
sans-seriftrue
fantasyfalse
defaulttrue
Arialtrue
Arial Blackfalse
Arial Narrowfalse
Arial Rounded MT Boldfalse
Bookman Old Stylefalse
Bradley Hand ITCfalse
Centuryfalse
Century Gothicfalse
Comic Sans MSfalse
Couriertrue
Courier Newtrue
Georgiafalse
Gentiumfalse
Impactfalse
Kingfalse
Lucida Consolefalse
Lalitfalse
Modenafalse
Monotype Corsivafalse
Papyrusfalse
Tahomafalse
TeXfalse
Timestrue
Times New Romantrue
Trebuchet MSfalse
Verdanafalse
Veronafalse

==========================================利用flash交互===================================================================

再有一种广泛而常用的方式是使用flash来获取系统支持字体……因为flash就当前来看,是不愁得到支持的……在网上搜了一下,比较多的用flash获取系统字体并显示的方法是这样的:

[javascript] view plain copy
  1. import flash.text.Font;  
  2. var fontList:Array = Font.enumerateFonts(true);  
  3. fontList.sortOn("fontName", Array.CASEINSENSITIVE);  
  4. for each(var font:Font in fontList)trace(font.fontName);  
好吧,这是基于AS3的……我的flash工具太落后了,还是几年前的Micromedia flash 8.0,还不支持AS3……好吧,咱用AS2……
那就是这样的:
[javascript] view plain copy
  1. var font_array:Array = TextField.getFontList();  
  2. font_array.sort();  
  3. trace("You have "+font_array.length+" fonts currently installed");  
  4. trace("--------------------------------------");  
  5. for (var i = 0; i<font_array.length; i++)  
  6.     trace("Font #"+(i+1)+":\t"+font_array[i]);  
好了,下一步就是与js嫁接了……参考某老外的文章,并参考flash8自带的帮助文档……
我了解到flash是通过内置的flash.external.ExternalInterface类来解决与js互相调用的问题……那么flash的代码可能是这个样子的:
[javascript] view plain copy
  1. import flash.external.ExternalInterface;  
  2. //声明js可以使用getAllFonts这个函数名来调用本flash中的getAllFonts()方法  
  3. ExternalInterface.addCallback("getAllFonts"this, getAllFonts);  
  4. function getAllFonts():Array{  
  5. var font_array:Array = TextField.getFontList();  
  6. font_array.sort();return font_array;  
  7. }  
  8. import flash.external.ExternalInterface;  
  9. //声明js可以使用getAllFonts这个函数名来调用本flash中的getAllFonts()方法  
  10. ExternalInterface.addCallback("getAllFonts"this, getAllFonts);  
  11. function getAllFonts():Array{  
  12.     var font_array:Array = TextField.getFontList();  
  13.     font_array.sort();  
  14.     return font_array;  
  15. }  
  16. ExternalInterface.call("show");//调用js中的show方法  
那么js中就要实现show方法了,可能的代码:
[javascript] view plain copy
  1. function getMovie(movieName) {  
  2.     var isIE = navigator.appName.indexOf("Microsoft") != -1;  
  3.     return (isIE) ? window[movieName] : document[movieName];  
  4. }  
  5.   
  6.   
  7. function getFontList() {  
  8.     return getMovie("fontListFlash").getAllFonts();  
  9. }  
  10. function show(){  
  11.     var fonts=getFontList();  
  12.     var selectStr="<select οnchange='chooseFont(this.value)'>";  
  13.     for(var i=0;i<fonts.length;i++)  
  14.         selectStr+="<option value='"+fonts[i]+"'>"+fonts[i]+"</option>";  
  15.     selectStr+="<select>";  
  16.     document.getElementById("outDiv").innerHTML=selectStr;  
  17. }  
  18. function chooseFont(v){  
  19.     document.body.style.fontFamily="'"+v+"'";  
  20. }  
当然,为了防止出现undefined的情况,这些函数的声明位置最好在flash插入位置之前……
好吧,我承认我在插入flash的时候出现了一些不兼容的情况……不过……功夫不负有心人,我终于找到了兼容的插入flash的方法:
  1. <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"  width="14" height="14">  
  2.     <param name="quality" value="high">  
  3.     <param name="bgcolor" value="green">  
  4.     <param name="allowFullScreen" value="false">  
  5.     <param name="swLiveConnect" value="true">  
  6.     <param name="allowScriptAccess" value="sameDomain">  
  7.     <param name="wmode" value="transparent">  
  8.     <embed type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" width="14" height="14" bgcolor="red" name="fontListFlash" src="fontlist.swf" flashvars="" style="border:1px solid black;"></embed>  
  9. </object> 


相关的flash源码
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值