2009-11-13 73 views
0

我正在嘗試編寫一些jQuery代碼,它將通過在其周圍添加邊框來突出顯示光標當前懸停的元素。這裏是我到目前爲止的代碼:使用jQuery來「突出顯示」光標下的內容

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Hover Test</title> 
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> 
<script> 
    $(function() { 
     $("*:not(html, head, body)").hover(function() { 
      $(this).css("border", "2px solid purple"); 
     }, 
     function() { 
      $(this).css("border", "none"); 
     }).click(function() { 
      alert($(this).html()); 
     }); 
    }); 
</script> 
</head> 

<body> 
<div> 
    <p>This is paragraph one</p> 
    <p>This is paragraph two</p> 
</div> 
<span id="curtag"></span> 
</body> 
</html> 

問題是,當我將鼠標懸停在類似的例子中爲段落下方也凸現在這種情況下,DIV父標籤。此外,當我點擊段落時,它會給我p的html,然後是div的html,但是,我只想要p標記中的html。對於如何解決這個問題,有任何的建議嗎?

回答

1

添加

return false; 

這樣

$(function() { 
    $("*:not(html, head, body)").hover(function() { 
      $(this).css("border", "2px solid purple"); 
    return false; 
    }, 
    function() { 
      $(this).css("border", "none"); 
    }).click(function() { 
      alert($(this).html()); 
      return false; 
    }); 
}); 

從bubbeling父停止mouseOver事件。

+0

感謝您的回覆。這很有效,唯一的就是如果說我擁有它,所以它突出顯示了div的拳頭,然後進入段落標記div仍然突出顯示,因爲我還沒有完全停止在它上面。 – blcArmadillo 2009-11-15 22:32:09

0

您對於允許觸發懸停()事件的元素過於籠統。當你說the element the cursor is currently hovering over時,它指的是幾個嵌套元素,它們都適當地獲得邊界。

如果您只有<p>的文本,爲什麼不讓他們獨自觸發邊界?

$('p').hover(function() { etc.....