开发者

Select the littlest hovered element with JQuery

I guess the question is in the title: I want to apply a style only to the开发者_JAVA百科 littlest hovered element when the user clicks. How do do I choose this very element ?

Thanks.


To put a style on the div and not have the parent affected, you can stop the bubble with event.stopPropagation(), like this:

$("div").click(function(e) {
  $(this).toggleClass("myClass");
  e.stopPropagation();
});

You can see a demo of this working here

For the hover case, you actually would want mouseover and mouseout instead of mouseenter and mouseleave (which .hover() binds to) in this case, like this:

$("div").mouseover(function(e) {
  $(this).addClass("myClass").parents().removeClass("myClass");
  e.stopPropagation();
}).mouseout(function() {
  $(this).removeClass("myClass");
});​

You can see this in action here

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜