如何通过document.body.style在JavaScript中实现@import导入?
问题解决:动态导入字体并应用到目标元素
原代码的问题
document.body.style.import url(...)完全错误:行内样式(element.style)不支持CSS的@import规则,@import只能在<style>标签或外部CSS文件中使用。document.getElementById(applyFont)不符合预期:当传入"h1"时,这个方法会寻找id为h1的元素,而非所有<h1>标签。document.getElementById(applyFont).style.fontFamily = ;语法错误,未指定字体名称。
修正后的实现代码
function font(fontData) { const fontName = fontData.font; const targetSelector = fontData.text; // 动态创建link标签导入Google Fonts字体 const link = document.createElement('link'); link.rel = 'stylesheet'; // 替换字体名称中的空格为+,适配Google Fonts的URL格式 link.href = `https://fonts.googleapis.com/css2?family=${fontName.replace(/\s+/g, '+')}&display=swap`; // 避免重复导入同一字体 if (!document.querySelector(`link[href*="${fontName.replace(/\s+/g, '+')}"]`)) { document.head.appendChild(link); } // 获取所有目标元素并设置字体 const targetElements = document.querySelectorAll(targetSelector); targetElements.forEach(element => { // 包裹字体名称,兼容带空格的字体(如"Open Sans"),添加后备字体 element.style.fontFamily = `"${fontName}", sans-serif`; }); }
使用示例
font({ "font": "Ubuntu", "text": "h1" // 作用于页面中所有<h1>元素 })
关键说明
- 用
<link>标签替代@import:动态创建link是更高效的字体导入方式,不会阻塞页面渲染,也更符合现代前端实践。 - 支持通用选择器:
querySelectorAll可以处理标签、类、ID等各种CSS选择器,比单一的getElementById更灵活。 - 重复导入检查:避免多次调用函数时重复添加相同的字体链接。
- 字体名称处理:用引号包裹字体名,适配带空格的字体;添加
sans-serif作为后备,确保字体加载失败时页面仍正常显示。
内容的提问来源于stack exchange,提问作者LouisGoldean
相关产品推荐
相关产品推荐

