2014-10-17 42 views
2

我正在寫一個小文件,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),雖然這看起來不太整齊。

是否有這些「跳入頁面」的事件?如果沒有,那麼達成這種效果的好方法是什麼?

+2

我認爲'scroll'事件就是你想要的。 – Barmar 2014-10-17 03:34:38

+0

@Barmar事件只是通過滾動來觸發,對吧?雖然在這種情況下不會導致問題,因爲'#'後面的內容總是被選中,我是否理解沒有特殊的「跳躍,不滾動」方式? – Yosh 2014-10-17 03:38:05

+0

我不完全確定。我認爲它可能引發窗口重新定位的任何事情,而不僅僅是使用滾動條。嘗試一下,看看它是否有效。 – Barmar 2014-10-17 03:39:12

回答

2

沒有一件事會涉及您的用例,但由於您只是試圖設計一個有針對性的元素,所以您實際上可以利用CSS僞類的:target。所述MDN documentation有着相當不錯的說明和一些例子:

的URI與片段標識符鏈接到 文檔內的特定元件,被稱爲目標元素。例如,以下是指向名爲section2的錨的URI : http://example.com/folder/document.html#section2錨可以是任何具有id屬性的 元素,例如,在我們的例子中爲<h1 id="section2">。 目標元素h1可以用:target僞類來表示。

:target僞類也與命名錨工程(即<a name="some-id-value"></a>),所以它與舊標記向後兼容。但是,您會注意到,使用已命名的錨點是而不是 100%相同 - 目標項目接收該規則,錨點是內聯元素。

這裏的@金王的例子,包括作爲代碼片段:

:target { 
 
    background: #eeeeaa; 
 
}
<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>

一個需要注意的是,IE8下不支持:target選擇。你可以通過使用填充如SelectivirIE9.js來解決這個問題。

相關問題