jquery - 避免将样式应用于 :after when using :hover

标签 jquery css pseudo-element css-content

<分区>

我正在使用 :after 为自己设置一个带有半径和渐变的边框,例如:

 #main .element {
      border-radius: 10px;
      background: #FFF;
    }

 #main .element:after {
      border-radius: 10px;
      background: linear-gradient(red, blue);
      top: -7px;
      bottom: -7px;
      left: -7px;
      right: -7px;
      z-index:-1;
    }

我希望相关元素在悬停时更改其背景颜色,例如:

#main .element:hover {
  background: #F00;
}

问题是 :after 伪元素也被选中,并且它的背景也发生了变化 - 我不希望 :after 样式在悬停在元素上时受到影响 - 我希望边框保持其背景颜色。 关于如何执行此操作的任何建议?我更愿意使用 CSS,但我不反对在需要时使用 jquery。谢谢

最佳答案

问题不在于 :after 是从父级继承样式,如 this jsfiddle shows .
您的问题是 :after 的 css 缺少几个关键属性:

#main .element:after {
  /* :before and :after elements *must* have `content` set, even if it is empty*/
  content: "";
  border-radius: 10px;
  background: linear-gradient(red, blue);
  /* :after also doesn't have any size, since you never position it. Without a non-static position, top, bottom, etc. are ignored*/
  position:absolute;
  top: -7px;
  bottom: -7px;
  left: -7px;
  right: -7px;
  z-index: -1;
}

关于jquery - 避免将样式应用于 :after when using :hover,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34047904/

上一篇:html - css - 删除单元格中行之间的间距

下一篇:jquery - 使用 jQuery 隐藏 div 并持续选择 onchange

相关文章:

CSS垂直扩展元素并移动伪元素

javascript - jQuery 仅返回 <li> 元素文本

css - 动态设置 CSS padding-top

css - LESS 中的直接子选择器

pseudo-element - CSS 虚线阴影

html - 伪元素在 chrome 中消失但在 firefox 中不消失

javascript - Jquery remove() 动态创建的元素

php - 加载 ajax 内容后 jquery 工具提示不起作用

jquery - 将类添加到 var jquery

jquery - 在 div 中定位元素