1

下面的 HTML 在我的网站上显示了一种花哨的字体,因为我做了一些改动<h2>

<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>​

这在网站上显示得很好。

Fancy Header 2 字体

当用户现在转到任务栏并选择其中一个子菜单项时,<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 中的字符串的帮助。提前致谢!

CSS 样式表用于<h2>

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

h2 span {
    color: #8a8a8a;
}

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

4

2 回答 2

1

您的代码实际上正在替换

Welcome to <span>Pomona High School!</span>

Welcome to Pomona High School!

注意,没有元素。只需使用 span 标签设置它,就可以了。

于 2012-10-21T15:45:03.650 回答
0

来源: MDN 文档

以下是 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;

​</p>


好吧,我很困惑。在这个 JSFiddle中它对我有用时,一定还有其他事情发生......


您的代码删除了可能提供样式<span>的on hash 更改中的。<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>';
    }​
}

另外,我认为您混淆了ifandelse语句。这:

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

else {
    ...
}

真的应该是:

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

else if {
    ...
}
于 2012-10-21T15:45:16.000 回答