在没有重新加载的情况下,在页面内跳转的事件是什么?

时间:2014-10-17 03:30:22

标签: javascript html javascript-events

我正在写一个小文档,html就像:

<dl class="commands">
  <dt id="commandA">Command A</dt>
  <dd class="description">This command makes you happy.</dd>
  <dt id="commandB">Command B</dt>
  <dd class="description">This command makes you even happier.</dd>
</dl>

我认为如果访问mydoc.html#commandA高亮显示command A的描述并写入以下javascript会很好:

(function(){
  window.addEventListener('load', emphCmd);

  function emphCmd(){
    var loc = window.location.href;
    if (/\.html#.*$/.test(loc)){
      var cmd = loc.split("#")[1]; // "commandA" for mydoc.html#commandA
      var cmdElm = document.getElementById(cmd);
      if (cmdElm !== null){ // if element with that id is found,
        cmdElm.style.backgroundColor = "#eeeeaa"; // highlight its background.
      }
    }
  }
})();

这是有效的,但只有当页面被加载时(好吧,当然。我说在load上这样做)。此脚本不执行任何操作的情况包括:i)当我手动将#commandA添加到浏览器中的地址栏并按Enter键(不使用F5 ---重新加载)时ii)使用<a>标签跳转到页面内

我希望在任何一种情况下突出显示它。对于<a href="#commandA">,我可能anchor.addEventListener('click',emphCmd),虽然这看起来不是很整洁。

是否存在这些“在页面内跳跃”的事件?如果没有,实现这种效果的好方法是什么?

1 个答案:

答案 0 :(得分:2)

单个事件不会覆盖您的用例,但由于您只是尝试设置目标元素的样式,因此您实际上可以利用:target CSS伪类。 MDN documentation有一个非常好的描述和一些例子:

  

带有片段标识符的URI链接到其中的某个元素   文档,称为目标元素。例如,这是一个URI   指向名为section2的锚点:   http://example.com/folder/document.html#section2锚可以是任何锚   具有id属性的元素,例如我们的示例中为<h1 id="section2">。   目标元素h1可以由:target伪类表示。

:target伪类也适用于命名锚(即<a name="some-id-value"></a>),因此它与旧标记向后兼容。但是,您会注意到,使用命名锚点 100%相同 - 目标项目接收规则,锚点是内联元素。

此处的@KingKing示例,包含在代码段中:

&#13;
&#13;
:target {
  background: #eeeeaa;
}
&#13;
<a href="#commandA">Command A</a>
<a href="#commandB">Command B</a>
<a href="#commandC">Command C</a>
<dl class="commands">
  <dt id="commandA">Command A</dt>
  <dd class="description">This command makes you happy.</dd>
  <dt id="commandB">Command B</dt>
  <dd class="description">This command makes you even happier.</dd>
  <dt><a name="commandC">Command C</a></dt>
  <dd class="description">This command makes you sad, since it's using a named anchor.</dd>
</dl>
&#13;
&#13;
&#13;

一个警告是IE8及以下版本不支持:target选择器。您可以使用SelectivirIE9.js等填充物来解决这个问题。

相关问题