开发者

firebug like jquery implementation

I want to implement a firebug like highlight when my cur开发者_如何学编程sor hovers an element

$("*").mouseover(function()
{
    $(this).css({border:'1px solid blue'});
})
.mouseleave(function() 
{
    $(this).css({border: ''});
});

but it doesnt change the css when the cursor hovers an inner element, the outer element still has its style changed instead of reverting back to its original css due to mouseleave()


Don't do such heavy stuff on *. Use .delegate instead.

$('body').delegate('*', 'mouseover mouseout', function (e) {
    if (this === e.target) {
        $(e.target).css('border', (e.type === 'mouseover' ? '1px solid blue' : ''));
    }
});

I haven't tested it, but my point is to use .delegate.

Edit Added suggestion by Crowder (thanks!)


Like Noufal, my first thought was "better to do that with CSS's :hover pseudo-class" (unless you have to support IE6, which doesn't support :hover except on links), but I can't immediately think how you would handle making sure the ancestor elements didn't also have the border. And having the border on all the ancestors looks pretty ugly to me: http://jsbin.com/eveno4/2

For a JavaScript solution: You were close, but typically you'd use mouseover and mouseout, or use mouseenter and mouseleave, but not mouseover and mouseleave (not usually; there are places you would).

In this case, I'd probably use mouseover and mouseout, but only act on events actually triggered by the element in question (not bubbled ones):

$("*").mouseover(function(event)
{
  if (this === event.target) {
    $(this).css({border:'1px solid blue'});
  }
})
.mouseout(function(event) 
{
  if (this === event.target) {
    $(this).css({border:''});
  }
});

Live copy

Note the use of event.target to make sure we're not processing a bubbled event.

Or, rather than hooking up a handler to every element on the page, hook up the handlers just on the body element and take advantage of the fact that they bubble, using delegate:

$(document.body).delegate("*", "mouseover", function(event)
{
  if (this === event.target) {
    $(this).css({border:'1px solid blue'});
  }
})
.delegate("*", "mouseout", function(event) 
{
  if (this === event.target) {
    $(this).css({border:''});
  }
});

Live example

(Or you could use live, it largely comes to the same thing.)


Can't you do something like

*:hover {
     border: 1px solid blue;
} 

in your CSS rules rather than rely on Javascript?

Update. I just tried it and it seems to work reasonably well.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜