如何用JavaScript随机切换Google Fonts?按钮切换失效问题
字体切换按钮修复方案
问题根源
- 函数参数覆盖全局变量:
fontCharger函数定义时声明了fonts参数,点击按钮触发时未传参,导致函数内fonts为undefined;同时该参数覆盖了全局的字体数组。 - 随机取值逻辑错误:错误地把随机获取的字体名称当作数组索引,用
fonts[number]取值自然得到undefined。 - 字体名称格式不匹配:数组里的连字符命名(如
baloo-bhaina)和Google Fonts实际的字体名称(如Baloo Bhaina)不一致,无法正确匹配已导入的字体。
修复代码
修正后的JavaScript
const sizeUp = document.querySelector('.sizeUp') const sizeDown = document.querySelector('.sizeDown') const colorBtn = document.querySelector('.color') const fontBtn = document.querySelector('.font') const p = document.querySelector('p') let fontSize = 36 const increase = () => { if(fontSize>200) return fontSize += 5 p.style.fontSize = fontSize + 'px' } const decrease = () => { if(fontSize<=21) return fontSize -= 5 p.style.fontSize = fontSize + 'px' } const colorChanger = () => { const r = Math.floor(Math.random() * 255) const g = Math.floor(Math.random() * 255) const b = Math.floor(Math.random() * 255) p.style.color = `rgb(${r},${g},${b})` }; // 修正字体名称为Google Fonts对应的格式 const fonts = [ "Baloo Bhaina", "Josefin Slab", "Arvo", "Lato", "Volkhov", "Abril Fatface", "Ubuntu", "Roboto", "Droid Sans Mono", "Anton", ]; // 移除参数,修正随机索引逻辑 const fontCharger = () => { const randomIndex = Math.floor(Math.random() * fonts.length); // 添加fallback字体,确保兼容性 p.style.fontFamily = `"${fonts[randomIndex]}", sans-serif` } sizeUp.addEventListener('click', increase) sizeDown.addEventListener('click', decrease) colorBtn.addEventListener('click', colorChanger) fontBtn.addEventListener('click', fontCharger)
CSS(仅需确认@import链接正确,无需修改)
@import url('https://fonts.googleapis.com/css?family=Abril+Fatface|Anton|Arvo|Baloo+Bhaina|Droid+Sans+Mono|Josefin+Slab|Lato|Roboto|Ubuntu|Volkhov'); * { box-sizing: border-box; margin: 0; padding: 0; } body { display: flex; justify-content: center; align-items: center; flex-direction: column; height: 100vh; font-family: 'Montserrat', sans-serif; color: rgb(255, 255, 255); background-color: rgba(82, 82, 82); } div { padding: 50px; } p { font-size: 36px; }
HTML(无需修改)
<script src="https://kit.fontawesome.com/072211b0fb.js" crossorigin="anonymous"></script> <div class="buttons"> <button class="sizeUp">+</button> <button class="sizeDown">-</button> <button class="color">color</button> <button class="font">font</button> </div> <div class="text"> <p>Lorem ipsum dolor sit amet.</p> </div>
关键说明
- 字体名称必须和
@import链接中family=后的名称一致(把+换成空格即可),比如Baloo+Bhaina对应Baloo Bhaina。 - 设置
fontFamily时需要给带空格的字体名称加引号,否则浏览器无法识别。 - 添加
sans-serif作为fallback,防止字体加载失败时文本显示异常。
内容的提问来源于stack exchange,提问作者Katarzynkah A
相关产品推荐
相关产品推荐

