由于对<h2>进行了一些更改,以下HTML在我的网站上显示了精美字体

<section id="content">
    <article>
        <h2 id="titletext">Welcome to <span>Pomona High School!</span></h2>
        <p id="infotext" style="width: 773px; height: 28px;" >Welcome to the new Pomona High School site! Please give us feedback!</p>
        <br />
    </article>
</section>​


这在站点中显示得很好。



现在,当用户转到任务栏并选择子菜单项之一时,<h2>文本将更改为指定的字符串值。我进入Javascript编辑器并产生了以下内容。

window.onhashchange = function() { //when the hash changes (the '#' part)
    var loc = window.location + ""; //get the current location (from the address bar)
    var curHash = loc.substr(loc.lastIndexOf("#")); //get what's after the '#'
    if (curHash == "#mission") { //else if it's #mission
        document.getElementById('titletext').innerHTML = 'Mission Statement';
    }

    else {
        document.getElementById('titletext').innerHTML = 'Welcome to Pomona High School';

    }
};​


将菜单项之一链接到#mission,我成功地更改了文本。但是字体更改为默认的<h2>字体。

我需要有关如何将自定义字体带入Javascript字符串中的帮助。提前致谢!

<h2>的CSS样式表:

h2 {
    font-size: 30px;
    line-height: 1.2em;
    font-weight: normal;
    color: #212222;
    margin-bottom: 22px;
}

h2 span {
    color: #8a8a8a;
}


这是两个自定义字体文件(太大,无法复制和粘贴到Stack Overflow):


Regular Font
Light Font

最佳答案

资料来源:MDN Docs


这是MDN必须说的:


  窗口的哈希值更改时,将触发hashchange事件(请参见
  location.hash)。
  
  句法:-
  
  
  window.onhashchange = funcRef;
  <body onhashchange="funcRef();">
  window.addEventListener("hashchange", funcRef, false);
  


我认为传递function() { ... }是函数引用,但是您可以先定义函数然后传递命名引用吗?该代码将去:

function hashChange() { //when the hash changes (the '#' part)
    var loc = window.location + ""; //get the current location (from the address bar)
    var curHash = loc.substr(loc.lastIndexOf("#")); //get what's after the '#'
    if (curHash == "#mission") { //else if it's #mission
        document.getElementById('titletext').innerHTML = 'Mission Statement';
    }

    else {
        document.getElementById('titletext').innerHTML = 'Welcome to Pomona High School';

    }
};

window.onhashchange = hashChange;






好,我很困惑。在this JSFiddle中,对于我来说,肯定还有其他事情正在发生...



您的代码将哈希更改中的<span>中的<h2>删除了,这大概是在提供样式。所以它实际上应该是:

window.onhashchange = function() { //when the hash changes (the '#' part)
    var loc = window.location + ""; //get the current location (from the address bar)
    var curHash = loc.substr(loc.lastIndexOf("#")); //get what's after the '#'

    if (curHash == "#mission") { //else if it's #mission
        document.getElementById('titletext').innerHTML = '<span>Mission Statement</span>';
    }

    else {
        document.getElementById('titletext').innerHTML = 'Welcome to <span>Pomona High School</span>';
    }​
}




另外,我认为您正在混淆ifelse语句。这个:

else if(curHash == "#mission") {
    ...
}

else {
    ...
}


确实应该是:

if(curHash == "#mission") {
    ...
}

else if {
    ...
}

09-28 09:58
查看更多