开发者

jQuery: add border on hovered element but NOT parents

I have this code:

var originalBorder = container.css("border");    
container.hover(function(event) {
            event.stopPropagation();
            $(this).css("border", "1px solid "+options.color);
       },function(){
            $(this).css("border", originalBorder);
       });

Which I am using to add a border to the currently hovered element. However for example if a span is inside a div they are both getting borders. I only want to target the span. I thought that adding event.stopPropagation() would do the trick (this is what I would do in Flex, which is what I am more used to) but I guess this is a live event which I dont even understand what that means. So basically how can target the youngest element without triggering the parents?

Thanks!!

update

Some more info. I am trying to add this effect to every element. so I am actually added the effect to the div and the span but I only want the div to be triggered when it is the youngest element that is hovered. And when a younger element is hovered like a span开发者_StackOverflow社区 within a div then only the span is triggered. The code above is a plugin and I am calling it like this: #("*").doBorders()


I think it's just a matter that your selector is selecting the container.

If you can, make sure the first selector is selecting the child--the child that you want to manipulate...

something like this:

    $(".childSpanClass").hover(
        function () {
            $(this).css("border", "1px solid "+options.color);
        },
        function () {
            $(this).css("border", originalBorder);
        }
    );

If you can't select the child there, then you could select the child inside the functions, like this:

    $(".container").hover(
        function () {
            $(this).children(".childClass").css("border", "1px solid "+options.color);
        },
        function () {
            $(this).children(".childClass").css("border", originalBorder);
        }
    );

Update: Given your update, you might want to try going at it from the point of view of the child clearing the parents borders:

$(".container").hover(
    function () {
        $(this).parents().css("border", "");
        $(this).css("border", "1px solid blue");
    },
    function () {
        $(this).css("border", "");
    }
);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜