CSS / On hover,我可以更改相同的元素:: after吗?

时间:2018-01-10 05:59:21

标签: html css drop-down-menu styles dropdown

我有class =“dropdown-button”的标签,并希望在第一个LI元素悬停后设置其:: after。

我正在尝试这个:

<ul class="dropdown-button">
   <li> home </li>
   <li> about us </li>
</ul>

style {

   .dropdown-button {
     margin-top:10px;
     border:1px solid #ccc;
    }  

  .dropdown-button::after {
    border-bottom: 6px solid #FFFFFF;
    border-left: 6px solid rgba(0, 0, 0, 0);
    border-right: 6px solid rgba(0, 0, 0, 0);
    content: "";
    display: inline-block;
    left: 7px;
    position: absolute;
    top: -6px;
   }

   // To solve problem, I do this :
   .dropdown-button li:first-child:hover .dropdown-button::after{
     border-bottom: 6px solid #a1a2a3;
     content: "";
    }

    //But this doesn't work.

}

有什么建议吗?

4 个答案:

答案 0 :(得分:1)

这在js:

var el = $('.dropdown-button');
var firstChild = el.children().first();

firstChild.on('mouseover', onMouseOver);
firstChild.on('mouseout', onMouseOut);

function onMouseOver() {
    el.addClass('first-child-hovered');
}

function onMouseOut() {
    el.removeClass('first-child-hovered');
}

然后在css:

.first-child-hovered::after {
    // change style here
}

答案 1 :(得分:0)

简单代码:

.dropdown-button li:first-child:hover::after{
     border-bottom: 6px solid #a1a2a3;
     content: "";
}

答案 2 :(得分:0)

嗯,深刻的答案是:通过纯粹的CSS无法通过子类的伪类影响父类的伪类。它的名称:级联样式表仅支持级联方向的样式,而不支持其父级。 所以这是一个更好的解决方案。在

中引入一个新的span元素,给它:after伪元素属性,并在列表项的第一个孩子的悬停时,显示你的新元素。解决方案全部用CSS。 请按照以下代码段进行操作:

&#13;
&#13;
    .dropdown-button {
         margin-top:10px;
         border:1px solid #ccc;
         position: relative;
        }  
    
      .dropdown-button:after {
        border-bottom: 6px solid #FFFFFF;
        border-left: 6px solid rgba(0, 0, 0, 0);
        border-right: 6px solid rgba(0, 0, 0, 0);
        content: "";
        display: inline-block;
        left: 7px;
        position: absolute;
        top: -6px;
        transition: border-bottom 0.5s ease;
        z-index: 0;
       }
    
      .dropdown-button1:after {
        
        border-bottom: 6px solid red;
        border-left: 6px solid rgba(0, 0, 0, 0);
        border-right: 6px solid rgba(0, 0, 0, 0);
        content: "";
        display: none;
        left: 7px;
        position: absolute;
        top: -6px;
        z-index: 3;
       }
       li:first-child:hover ~ .dropdown-button1:after {
         border-bottom: 6px solid #a1a2a3;
         display: inline-block;
    }
&#13;
    <ul class="dropdown-button">
       <li> home </li>
       <li> about us </li>
       <span class="dropdown-button1"></span>
    </ul>
&#13;
&#13;
&#13;

答案 3 :(得分:-1)

您可以使用jQuery

来完成此操作
$(".dropdown-button").first('li').hover(function(){
   $(this).parent().addClass('hovered');
})

//CSS
.hovered:after {
   border-bottom: 6px solid #a1a2a3;
   content: "";
}