如何在翻转时更改选择器的Pseudo-element的背景颜色?

时间:2013-06-11 19:04:32

标签: jquery css3 shape pseudo-element

我的CodePen: http://codepen.io/leongaban/pen/cfLEh

我在CSS shapes上创建了一个“尖头标志”按钮。

基本上arrow-button有背景颜色,而arrow-button:before会在框右侧为三角形创建背景。

我想在悬停或鼠标中心将整个形状的背景颜色从蓝色变为橙色。

enter image description here

你会怎么做呢?

CSS

#arrow-button {
   width: 120px; 
   height: 57px; 
   background: blue;
   position: relative;
   left: 200px;
   cursor: pointer;
}
#arrow-button:before {
   content:"";
   position: absolute;
   width: 0;
   height: 0;
   border-top: 28.5px solid transparent;
   border-left: 10px solid blue;
   border-bottom: 28.5px solid transparent;
   margin: 0 15px 0 120px;
}

的jQuery

$('#arrow-button').mouseenter( function(){
  $('#arrow-button')
     .css(
      'background', 
      '#fc8236');
  $('#arrow-button:before')
    .css(
       'border-left', 
      '10px solid #fc8236');
});

$('#arrow-button').mouseleave( function(){
  $('#arrow-button')
    .css(
      'background', 
      'blue');
});

3 个答案:

答案 0 :(得分:2)

根本不需要js:

#arrow-button {
   width: 120px; 
   height: 57px; 
   background: blue;
   position: relative;
   left: 200px;
   cursor: pointer;
}
#arrow-button:before {
   content:"";
   position: absolute;
   width: 0;
   height: 0;
   border-top: 28.5px solid transparent;
   border-left: 10px solid blue;
   border-bottom: 28.5px solid transparent;
   margin: 0 15px 0 120px;
}

#arrow-button:hover {
   background: orange;
}

#arrow-button:hover:before {

  content:"";
   position: absolute;
   width: 0;
   height: 0;
   border-top: 28.5px solid transparent;
   border-left: 10px solid orange;
   border-bottom: 28.5px solid transparent;
   margin: 0 15px 0 120px;

}

答案 1 :(得分:1)

您只能使用 css 执行此操作:

#arrow-button:hover {
   width: 180px; 
   height: 57px; 
   background: #fc8236;
   position: relative;
   left: 200px;
   text-align: center;
   cursor: pointer;
}

#arrow-button:hover:before {
   content:"";
   position: absolute;
   width: 0;
   height: 0;
   border-top: 28.5px solid transparent;
   border-left: 10px solid #fc8236;
   border-bottom: 28.5px solid transparent;
   margin: 0 15px 0 134px;
}

答案 2 :(得分:1)

您可以将类附加到#arrow-button,以更新:before伪元素的边框颜色:

<强> CSS

#arrow-button.orange {
  background-color: #fc8236;
}

#arrow-button.orange:before {
  border-left: 10px solid #fc8236;
}

<强>的jQuery

$('#arrow-button').mouseenter( function(){
  $('#arrow-button').addClass('orange');
});

$('#arrow-button').mouseleave( function(){
  $('#arrow-button').removeClass('orange');
});