1

我是 Javascript(但不是 HTML 或 CSS)的新手,我正在尝试使用Lalit Patel的这个脚本来检测用户系统上是否安装了字体,如果没有,则提供修改后的样式表。我已经成功地让第一部分工作:我上传了 fontdetect.js 文件,在我的标题中调用它,然后在我的 body 标签结束之前粘贴它:

<script type="text/javascript">
window.onload = function() {
    var detective = new Detector();
    alert(detective.detect('Courier'));
};
</script>

(以 Courier 为例。)这会导致在页面加载时弹出警报,告诉我是否安装了字体,并且效果很好。但我不知道如何让脚本获取不同的样式表,而不是触发警报。这似乎是基本的东西,但我在任何地方都找不到细节,即使我一直在研究 Javascript 教程。任何指导将不胜感激!

如果需要更多细节:如果用户没有安装自定义字体或完全关闭自定义字体,我想使用 CSS 更改文本的大小/间距属性,以便后备字体能够以适应同一个空间。

4

3 回答 3

3
var detective = new Detector();
if (!detective.detect('Courier')){
  var s = document.createElement('link');
  s.rel = 'stylesheet';
  s.type = 'text/css';
  s.media = 'all';
  s.href = '/link/to/alternative/stylesheet.css';
  document.getElementsByTagName('head')[0].appendChild(s);
}

猜测是这样的。如果.detect()失败,它将动态创建样式表并将其插入页面。如果遇到问题,也可以使用.setAttribute()off 的s元素。

于 2013-04-03T14:49:35.530 回答
1

您可以使用 JS 向网站添加样式表:

var detective = new Detector();

if (!detective.detect('Courier')){    
     document.createStyleSheet('location/stylesheet.css');
}
else
{
     document.createStyleSheet('location/otherstylesheet.css');
}

因此,您可以检查检测器是否返回 true,如果不加载一种样式,则加载另一种样式。

于 2013-04-03T14:49:36.797 回答
1

在尝试了所有提供的方法之后,这是对我有用的方法(来自这个答案,但它实际上是这里提供的两个答案的混合)。应该注意的是,这在 IE8 中有效,与大多数其他方法不同(遗憾的是,我确实需要 IE8 兼容性)。

<script type="text/javascript">
    window.onload = function() {
        var detective = new Detector();
        if (!detective.detect('Meat')){
            var url = 'link/to/style.css'
            if(document.createStyleSheet) {
                try { document.createStyleSheet(url); } catch (e) { }
            }
            else {
                var css;
                css         = document.createElement('link');
                css.rel     = 'stylesheet';
                css.type    = 'text/css';
                css.media   = "all";
                css.href    = url;
                document.getElementsByTagName("head")[0].appendChild(css);
            }
        }
    };
</script>

这检测到我的浏览器不接受嵌入字体(“Meat”是我嵌入的字体之一)并提供了备用 CSS(尽管有轻微的延迟/无样式文本闪烁,可能是因为它位于页面底部?)无论如何,再次感谢所有的帮助!

于 2013-04-04T10:53:39.580 回答