如果孩子是img,则更改a:after样式

Change a:after style if child is img

本文关键字:after 样式 孩子 img 如果      更新时间:2023-09-26

我通过应用带有:after伪属性的内容来样式化悬停锚,它在下面添加了一个边框:

a:hover {
    position: relative; }
    a:hover:after {
        content: '';
        position: absolute;
        left: 0;
        display: inline-block;
        height: 1em;
        width: 100%;
        border-bottom: 1px solid #a5cf4c;
        margin-top: 0.5em; }

这工作得很好,但也有一些锚周围的图像,我不希望在他们下面的边界。对于CSS,这只适用于不存在的父选择器a:after < img。我试着用jQuery解决它,但是

不能操作:after,因为从技术上讲,它不是DOM的一部分,因此任何JavaScript都无法访问。参见访问css ":after"

我看了一些没有父母障碍的解决方案,但我不能得到任何地方。有人知道吗?

您可以添加after与一个类。

$('a:not(:has(img))').addClass('after-affect');
a:hover {
  position: relative;
}
a.after-affect:hover:after {
  content: '';
  position: absolute;
  left: 0;
  display: inline-block;
  height: 1em;
  width: 100%;
  border-bottom: 1px solid #a5cf4c;
  margin-top: 0.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Anchor with text -->
<a href="#">test</a>
<!-- Anchor with image -->
<a href="#">
  <img src="http://blog.grio.com/wp-content/uploads/2012/09/stackoverflow.png"/>
  </a>