Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
500 views
in Technique[技术] by (71.8m points)

jquery - Changing the child element's CSS when the parent is hovered

First of all, I'm assuming this is too complex for CSS3, but if there's a solution in there somewhere, I'd love to go with that instead.

The HTML is pretty straightforward.

<div class="parent">
    <div class="child">
        Text Block 1
    </div>
</div>

<div class="parent">
    <div class="child">
        Text Block 2
    </div>
</div>

The child div is set to display:none; by default, but then changes to display:block; when the mouse is hovered over the parent div. The problem is that this markup appears in several places on my site, and I only want the child to be displayed if the mouse is over it's parent, and not if the mouse is over any of the other parents (they all have the same class name and no IDs).

I've tried using $(this) and .children() to no avail.

$('.parent').hover(function(){
            $(this).children('.child').css("display","block");
        }, function() {
            $(this).children('.child').css("display","none");
        });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why not just use CSS?

.parent:hover .child, .parent.hover .child { display: block; }

and then add JS for IE6 (inside a conditional comment for instance) which doesn't support :hover properly:

jQuery('.parent').hover(function () {
    jQuery(this).addClass('hover');
}, function () {
    jQuery(this).removeClass('hover');
});

Here's a quick example: Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...