如果直接孩子是一个段落,请突出显示。如果是图像,请添加边框

时间:2011-07-20 06:19:50

标签: jquery

我有以下代码:

$(".highlight").hover(function(){
                $(this).css("background-color","#E3EBC2");
                },function(){
                $(this).css("background-color","transparent");
                });

我想知道如何突出显示此类的直接孩子是否为段落,如果是图像则添加边框

<div class = "highlight>
<p>
some text
</p>
</div>

所以直接的孩子将是p(树下只有一个级别)

4 个答案:

答案 0 :(得分:1)

$(.highlight:first-child p)

$(.highlight:first-child img)

可能会工作。

答案 1 :(得分:1)

一种方法是将child selectorfirst child filter合并,然后使用is调用来查看您获得的内容,如下所示:

$('.highlight').hover(
    function() {
        var $child = $(this).find('> :first-child');
        if($child.is('p'))
            $child.css("background-color", "#E3EBC2");
        else if($child.is('img'))
            $child.css('border', '3px solid #E3EBC2');
    }, function() {
        var $child = $(this).find('> :first-child');
        if($child.is('p'))
            $child.css("background-color", "transparent");
        else if($child.is('img'))
            $child.css('border', 'none');
    }
);

一个实例:http://jsfiddle.net/ambiguous/kSmXQ/

或者,如果你想玩一些CSS:

.highlight.highlighted > p {
    background-color: #E3EBC2;
}
.highlight.highlighted > img {
    border: 3px solid #E3EBC2;
}

和jQuery一起去:

$('.highlight > p:first-child, .highlight > img:first-child').parent().hover(
    function() {
        $(this).addClass('highlighted');
    }, function() {
        $(this).removeClass('highlighted');
    }
);

这个版本的实时版本:http://jsfiddle.net/ambiguous/LPga3/1/

感谢Ghostoy了解这一背后的想法。


如果您想要<div>而不是<p><img>孩子的背景颜色或边框更改:

$('.highlight').hover(
    function() {
        var $this  = $(this);
        var $child = $this.find('> :first-child');
        if($child.is('p'))
            $this.css("background-color", "#E3EBC2");
        else if($child.is('img'))
            $this.css('border', '3px solid #E3EBC2');
    }, function() {
        var $this  = $(this);
        var $child = $this.find('> :first-child');
        if($child.is('p'))
            $this.css("background-color", "transparent");
        else if($child.is('img'))
            $this.css('border', 'none');
    }
);

这个实例:http://jsfiddle.net/ambiguous/ufLaW/

答案 2 :(得分:1)

如果要突出显示.highlight元素(<div>)而不是直接子元素(<p><img>),则可能应使用此代码:http://jsfiddle.net/ghostoy/LPga3/

CSS:

.hlbackground {
    background-color: #E3EBC2;
}

.hlborder {
    border: 3px solid #E3EBC2;
}

jQuery的:

$('.highlight > p:first-child').parent().hover(
    function() {
        $(this).addClass('hlbackground');
    }, function() {
        $(this).removeClass('hlbackground');
    }
);

$('.highlight > img:first-child').parent().hover(
    function() {
        $(this).addClass('hlborder');
    }, function() {
        $(this).removeClass('hlborder');
    }
);

答案 3 :(得分:0)

$(".highlight").hover(function(){
    $('p', this).css("background-color","#E3EBC2");
},function(){
    $('img', this).css("border","solid");
});