<link href="http://www.example.com/style.css" rel="stylesheet" type="text/css">
但如果跨域了,大家该如何使用外部CSS文件呢?有以下两种方法:
1. 通过CORS(跨域资源共享)来加载CSS文件。只需要在服务器端设置好Access-Control-Allow-Origin头,就可以允许指定的源请求CSS文件了。
AddHandler application/x-httpd-php .css
Header set Access-Control-Allow-Origin "*" //允许所有请求
2. 将CSS文件作为JavaScript中的字符串,然后动态添加到HTML的标签中。
fetch('http://www.example.com/style.css')
.then(response =>response.text())
.then(css =>{
const style = document.createElement('style');
style.innerHTML = css;
document.head.appendChild(style);
});
以上两种方法包括了在不同浏览器中解决CSS跨域的问题,可根据具体需求选择。