CSS - 我可以这样使用@font-face吗:

CSS - can I use @font-face like this:

我想使用其他网站的字体url,可以吗?

@font-face {
    font-family: 'font';
    src: url('http://example.com/font.eot?#') format('eot'),    
         url('http://example.com/font.woff') format('woff'),     
         url('http://example.com/font.ttf') format('truetype');  
    font-weight: normal;
    font-style: normal;
}

我试过了,但没用!

不,您不能从另一个 URL 导入字体 文件 ,因为它 violates cross origin specs。您必须将 css 文件放在该域的同一目录中 (http://example.com/fonts.css):

/*fonts.css*/

@font-face {
    font-family: 'font';
    src: url('font.eot?#') format('eot'),    
         url('font.woff') format('woff'),     
         url('font.ttf') format('truetype');  
    font-weight: normal;
    font-style: normal;
}

然后在您的样式表中导入它:

@import url("http://example.com/fonts.css");

或者,link 在您的文档中 <head>:

<link rel="stylesheet" href="http://example.com/fonts.css">

您不能 从其他服务器导入任何脚本或字体,如果各自已在配置中禁用 CORS

只有 如果您可以访问另一台服务器,您可以通过以下方式启用它:

# Microsoft IIS in web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>
</configuration>

# Apache config
# The code can be placed with the `.htaccess` file or `httpd.conf` file:
<FilesMatch ".(eot|ttf|otf|woff)">
    Header set Access-Control-Allow-Origin "*"
</FilesMatch>

# nginx config
if ($filename ~* ^.*?\.(eot)|(ttf)|(woff)$){
    add_header Access-Control-Allow-Origin *;
}

这会将 Access-Control-Allow-Origin CORS 配置设置为允许从所有域中提取。如果您只想为特定域提供字体,请用逗号列出特定域。如果浏览器更喜欢一种类型,您将希望适当地提供所有字体类型。

进一步阅读:Serving Fonts from CDN