将鼠标悬停在父div上以影响子元素的伪后元素。下划线动画

时间:2017-10-25 14:15:16

标签: javascript jquery html css css3

目前我可以将鼠标悬停在h1上并且它会加下划线,但是我想知道如果我将鼠标悬停在父div上,我是否可以激活h1后面的伪后跟元素?

我试图仅将线宽保留为h1。我尝试过的其他方法将占用div的全部宽度。

因此,当悬停在h2或h3上时,下划线在h1上变为活动状态。

这仅适用于CSS,还是需要使用Javascript?

.nav-underline {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.nav-underline:before, .nav-underline:after {
  content: '';
  position: absolute;
  width: 0%;
  height: 3px;
  top: 45%;
  margin-top: -0.5px;
  background: #000;

}

.nav-underline:hover {
    letter-spacing: 4px;
    transition: .35s;
}
.nav-underline:before {
  left: -2.5px;
}
.nav-underline:after {
  right: 2.5px;
  background: #000;
  transition: width 0.8s cubic-bezier(0.22, 0.61, 0.36, 1);
}

.nav-underline:hover:before {
  background: #000;
  width: 100%;
  transition: width 0.5s cubic-bezier(0.22, 0.61, 0.36, 1);
}

.nav-underline:hover:after {
  background: transparent;
  width: 100%;
  transition: 0s;

}
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css" rel="stylesheet"/>
<a class="imagereveal" href="#" rel="image goes here">
   <div class="nav-underline"><h1>Test</h1></div>
   <h2>Description</h2>
   <h3>Detail</h3>
</a>

https://jsfiddle.net/jvo8wo65/

2 个答案:

答案 0 :(得分:2)

由于您希望父a.imagereveal上的悬停状态触发效果而不是取决于.nav-underline本身上的悬停状态,您只需替换此选择器的所有实例:

.nav-underline:hover

......用这个:

.imagereveal:hover .nav-underline

在旁注中,您应该使用双冒号作为伪元素,即::after而不是:after ... unless you really need backwards compatibility with IE8 and below

请参阅下面的概念验证或fixed JSfiddle

.nav-underline {
  position: relative;
  display: inline-block;
  cursor: pointer;
}

.nav-underline::before, .nav-underline::after {
  content: '';
  position: absolute;
  width: 0%;
  height: 3px;
  top: 45%;
  margin-top: -0.5px;
  background: #000;

}

.imagereveal:hover .nav-underline {
    letter-spacing: 4px;
    transition: .35s;
}
.nav-underline::before {
  left: -2.5px;
}
.nav-underline::after {
  right: 2.5px;
  background: #000;
  transition: width 0.8s cubic-bezier(0.22, 0.61, 0.36, 1);
}

.imagereveal:hover .nav-underline::before {
  background: #000;
  width: 100%;
  transition: width 0.5s cubic-bezier(0.22, 0.61, 0.36, 1);
}

.imagereveal:hover .nav-underline::after {
  background: transparent;
  width: 100%;
  transition: 0s;

}
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.min.css" rel="stylesheet"/>
<a class="imagereveal" href="#" rel="image goes here">
   <div class="nav-underline"><h1>Test</h1></div>
   <h2>Description</h2>
   <h3>Detail</h3>
</a>

答案 1 :(得分:1)

是的,您只需将悬停移动到父元素

即可
.imagereveal:hover .nav-underline::before{
  background: #000;
  width: 100%;
  transition: width 0.5s cubic-bezier(0.22, 0.61, 0.36, 1);
}
.imagereveal:hover .nav-underline::after{
  right: 2.5px;
  background: #000;
  transition: width 0.8s cubic-bezier(0.22, 0.61, 0.36, 1);
}