在 Web 应用程序中,为用户提供可用字体的下拉列表,允许他们自定义字体,从而增强用户体验文本的外观。这种定制需要获取浏览器可以显示的字体列表。
幸运的是,这个问题有一个直观的解决方案。 JavaScript 提供了一种简单的方法来列出浏览器可以访问的所有字体。这是让用户能够选择自己喜欢的字体并根据自己的喜好定制网页的关键一步。
一位才华横溢的 JavaScript 开发人员创建了一个全面的解决方案,允许开发人员检测可用的字体浏览器中的字体。此方法使用比较特定字符的渲染宽度和高度的技术。通过交叉检查与默认字体的偏差,脚本可以准确确定特定用户指定字体的可用性。
此解决方案的代码可在 GitHub 上获取。
/** * JavaScript code to detect available availability of a * particular font in a browser using JavaScript and CSS. * * Author : Lalit Patel * Website: http://www.lalit.org/lab/javascript-css-font-detect/ * License: Apache Software License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * Version: 0.15 (21 Sep 2009) * Changed comparision font to default from sans-default-default, * as in FF3.0 font of child element didn't fallback * to parent element if the font is missing. * Version: 0.2 (04 Mar 2012) * Comparing font against all the 3 generic font families ie, * 'monospace', 'sans-serif' and 'sans'. If it doesn't match all 3 * then that font is 100% not available in the system * Version: 0.3 (24 Mar 2012) * Replaced sans with serif in the list of baseFonts */ /** * Usage: d = new Detector(); * d.detect('font name'); */ var Detector = function() { // a font will be compared against all the three default fonts. // and if it doesn't match all 3 then that font is not available. var baseFonts = ['monospace', 'sans-serif', 'serif']; //we use m or w because these two characters take up the maximum width. // And we use a LLi so that the same matching fonts can get separated var testString = "mmmmmmmmmmlli"; //we test using 72px font size, we may use any size. I guess larger the better. var testSize = '72px'; var h = document.getElementsByTagName("body")[0]; // create a SPAN in the document to get the width of the text we use to test var s = document.createElement("span"); s.style.fontSize = testSize; s.innerHTML = testString; var defaultWidth = {}; var defaultHeight = {}; for (var index in baseFonts) { //get the default width for the three base fonts s.style.fontFamily = baseFonts[index]; h.appendChild(s); defaultWidth[baseFonts[index]] = s.offsetWidth; //width for the default font defaultHeight[baseFonts[index]] = s.offsetHeight; //height for the defualt font h.removeChild(s); } function detect(font) { var detected = false; for (var index in baseFonts) { s.style.fontFamily = font + ',' + baseFonts[index]; // name of the font along with the base font for fallback. h.appendChild(s); var matched = (s.offsetWidth != defaultWidth[baseFonts[index]] || s.offsetHeight != defaultHeight[baseFonts[index]]); h.removeChild(s); detected = detected || matched; } return detected; } this.detect = detect; };
通过利用此方法,开发人员可以轻松创建允许无缝字体自定义的用户界面。让用户能够从综合列表中选择自己喜欢的字体,可以增强整体用户体验和对 Web 应用程序的满意度。
以上是如何使用 JavaScript 以编程方式列出 Web 浏览器中的可用字体?的详细内容。更多信息请关注PHP中文网其他相关文章!