You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS实现网站字体切换器:遍历标题标签遇undefined报错求助

解决字体切换器中标题遍历的报错问题

报错undefined is not an object (evaluating 'tagElement.style.fontFamily = fontsObj.headerFont')源于两处代码逻辑问题,以下是具体分析和修正方案:

错误分析

  1. DOM集合遍历方式错误
    getElementsByTagName()返回的是HTMLCollection类数组对象,使用for...in遍历会获取到集合的所有可枚举属性(如length、item方法等),这些属性并非DOM元素,因此访问style属性会触发报错。

  2. 事件绑定逻辑错误
    fontSelector.onchange = changeFontStyle(fontSelector);会立即执行changeFontStyle函数,并将返回值(undefined)赋值给onchange,而非在事件触发时调用函数。

修正后的代码

HTML(无需修改)

<select name="font-select" id="font-select">
  <option value='{"headerFont":"system-ui, -apple-system","bodyFont":"system-ui, -apple-system"}'>System & System</option>
  <option value='{"headerFont":"Lato","bodyFont":"Karla"}' selected="selected">Lato & Karla</option>
  <option value='{"headerFont":"Lora","bodyFont":"Lato"}'>Lora & Lato</option>
  <option value='{"headerFont":"Philosopher","bodyFont":"Mulish"}'>Philosopher & Muli(sh)</option>
</select>

JavaScript

function changeFontStyle(event) {
    const headerTags = ["h1", "h2", "h3", "h4", "h5", "h6"];
    const fontsObj = JSON.parse(event.target.value);
    
    // 更新标题字体:将HTMLCollection转为数组后遍历
    headerTags.forEach(tag => {
        const tagElements = document.getElementsByTagName(tag);
        Array.from(tagElements).forEach(element => {
            element.style.fontFamily = fontsObj.headerFont;
        });
    });
    
    // 更新body字体
    document.documentElement.style.fontFamily = fontsObj.bodyFont;
}

const fontSelector = document.getElementById("font-select");
fontSelector.addEventListener("change", changeFontStyle);

关键修改点

  • DOM集合遍历优化:用Array.from()将HTMLCollection转为数组,再通过forEach遍历,确保每次拿到的都是DOM元素;也可直接使用for...of循环遍历HTMLCollection。
  • 事件绑定修正:使用addEventListener绑定change事件,确保事件触发时才执行函数,同时通过event.target获取触发事件的下拉框元素。
  • 简化元素获取:直接用document.documentElement获取<html>元素,替代getElementsByTagName("html")[0]的写法。

内容的提问来源于stack exchange,提问作者I7T5

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 12:45:46