我想知道当元素的父元素被悬停时,是否可能改变子元素的样式,同时也要更改其css。为了使我的问题更清楚,我在下面写了一个基本的代码:
//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');
}
})
基本上,一旦用户进入父级空间使子元素的背景变成蓝色,一旦进入子级空间将背景从蓝色更改为黄色。
我看到有人评论为什么我不使用CSS,这是一个小解释:我无法选择父元素。我只能使用parents()从子元素中进行操作。由于CSS尚未支持parents()方法,因此我选择了jQuery。:)
#container .panel > div
。CSS绝对是这里的答案。此外,使用hover()
然后检查mouseenter
事件有点多余 - 只需使用on('mouseenter', fn)
即可。 - Rory McCrossan