Merge pull request #3324 from tangly1024/feat-iconfont

Iconfont
This commit is contained in:
tangly1024
2025-04-11 17:43:42 +08:00
committed by GitHub
2 changed files with 58 additions and 0 deletions

View File

@@ -10,6 +10,7 @@ import { initGoogleAdsense } from './GoogleAdsense'
import Head from 'next/head'
import ExternalScript from './ExternalScript'
import WebWhiz from './Webwhiz'
import IconFont from './IconFont'
/**
* 各种插件脚本
@@ -124,6 +125,8 @@ const ExternalPlugin = props => {
NOTION_CONFIG
)
const ENABLE_ICON_FONT = siteConfig('ENABLE_ICON_FONT', false)
// 自定义样式css和js引入
if (isBrowser) {
// 初始化AOS动画
@@ -184,6 +187,7 @@ const ExternalPlugin = props => {
<>
{/* 全局样式嵌入 */}
<GlobalStyle />
{ENABLE_ICON_FONT && <IconFont />}
{MOUSE_FOLLOW && <MouseFollow />}
{THEME_SWITCH && <ThemeSwitch />}
{DEBUG && <DebugPanel />}

54
components/IconFont.js Normal file
View File

@@ -0,0 +1,54 @@
import { siteConfig } from '@/lib/config'
import { loadExternalResource } from '@/lib/utils'
import { useRouter } from 'next/router'
import { useEffect } from 'react'
/**
* iconfont
*/
export default function IconFont() {
const router = useRouter()
useEffect(() => {
loadExternalResource('/webfonts/iconfont.js').then(u => {
console.log('iconfont loaded')
// 查找所有 <i> 标签且 class 包含 'icon-'
const iElements = document.querySelectorAll('i[class*="icon-"]');
iElements.forEach(element => {
const className = Array.from(element.classList).find(cls => cls.startsWith('icon-'));
if (className) {
// 创建新的 <svg> 元素
const svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
svgElement.setAttribute('class', 'icon');
svgElement.setAttribute('aria-hidden', 'true');
const useElement = document.createElementNS('http://www.w3.org/2000/svg', 'use');
useElement.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', `#${className}`);
svgElement.appendChild(useElement);
// 替换原来的 <i> 元素
element.replaceWith(svgElement);
console.log(`Replaced <i> with class "${className}" to <svg>`);
}
});
})
}, [router])
return <style jsx global>
{`
.icon {
width: 1.1em;
height: 1.1em;
vertical-align: -0.15em;
fill: currentColor;
overflow: hidden;
}
svg.icon {
display: inline;
}
`}</style>
}