开发者

Using jQuery to "highlight" content under cursor

开发者 https://www.devze.com 2022-12-11 14:59 出处:网络
I\'m trying to write some jQuery code that will highlight the element the cursor is currently hovering over by adding a border around it. Here is the code I have so far:

I'm trying to write some jQuery code that will highlight the element the cursor is currently hovering over by adding a border around it. Here is the code I have so far:

<!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>
&开发者_开发知识库lt;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>

The problem is when I hover over something like a paragraph in the example below it also highlights the parent tag in this case the div. Additionally, when I click on the paragraph it gives me the html of the p and then the html of the div, however, I only want the html in the p tag. Any suggestions on how to fix this?


add

return false;

like this

$(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;
    });
});

to stop the mouseOver event from bubbeling to the parent.


You're being too general in what elements you're allowing to trigger the hover() event. When you say the element the cursor is currently hovering over, that refers to several nested elements, which are appropriately all getting borders.

If you're only going to have text in <p>s, why not just have them alone trigger the border?

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号