2017-03-15 58 views
2

我想知道是否有可能改变它的元素被徘徊时的孩子的风格,而其CSS也被称为当其父母被徘徊?jQuery:风格悬停在父母()和孩子()

为了清楚我的问题,我写下了以下基本代码:

//styling child while mouse is inside child element 
$('child').on('hover', function(e){ 
    if (e.type == 'mouseenter'){ 
     $(this).css('background','yellow'); 
    } 
}) 

    // styling child while mouse is inside parent 
$('child').parents().on('hover', function (e){ 
    if (e.type == 'mouseenter'){ 
     $(this).css('background', 'blue'); 
    } 
}) 

所以,基本上,一旦用户进入父的空间,使孩子的BG蓝色,一旦进入孩子的空间,从改变蓝色到黄色bg。


我看到我为什么不使用CSS的评论,所以这是一个小的解释:我无法选择父元素。我只能从使用父母的孩子那里做()。只要css不支持父母()方法,但我去了jQuery。 :)

+1

为什么不直接用CSS做呢? –

+0

@ibrahimmahrir在我的情况下,我没有权力只选择它自己的父元素。我只能从孩子选择它,使用父母()。和CSS不支持这一点呢。 –

+0

@RachelNicolas如果你不能直接选择元素,那么当然你可以根据它们在DOM中的位置来选择它们,比如'#container .panel> div'。 CSS绝对是这里的答案。同样使用'hover()'然后检查'mouseenter'事件有点多余 - 只需要使用''('mouseenter',fn)' –

回答

1

CSS当家:

div { 
 
    padding: 20px; 
 
    border: 1px solid black; 
 
} 
 

 
/* something hovered that have .child as direct child => change .child color to blue */ 
 
*:hover > .child { 
 
    background-color: blue; 
 
} 
 

 
/* .child element hovered => override the above color and set it to yellow (note that the above rule is still taking effect when this is taking effect) */ 
 
.child:hover { 
 
    background-color: yellow; 
 
}
<div> 
 
    PARENT 
 
    <div class="child">CHILD</div> 
 
</div> 
 
<div> 
 
    PARENT 
 
    <div class="child">CHILD</div> 
 
</div> 
 
<div> 
 
    PARENT 
 
    <div class="child">CHILD</div> 
 
</div>

+0

我完全忘了*:悬停!它完全按照我的想法工作!万分感谢! –

0

是该行为你期待什么呢?

$('#child').parent().on('mouseover', function(e){ 
 
    if(this===e.target){ 
 
    $(this).children().css('background','blue'); 
 
    }else{ 
 
    $(this).children().css('background','yellow'); 
 
    } 
 
}).on('mouseout', function(e){  
 
    $(this).children().css('background', 'green'); 
 
});
#parent{ 
 
    width:200px; 
 
    height:100px; 
 
    background-color:#f00; 
 
} 
 

 
#child{ 
 
    width:30px; 
 
    height:30px; 
 
    background-color:green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="parent"> 
 
    <div id="child"></div> 
 
</div>

+0

是的,谢谢你的帮助! :) –