【问题标题】:Preventing hover on pseudo element - but pointer-events: none; doesn't do it防止悬停在伪元素上 - 但指针事件:无;不这样做
【发布时间】:2018-02-15 12:28:45
【问题描述】:

我在一行中有几个链接,我想在它们之间用破折号分隔。我选择使用::before 伪元素来实现这一点,并且效果很好。

但是,将鼠标悬停在分隔线上也会触发悬停在我打开了::before 的元素上。

This is a fiddle showing the issue. 如果将鼠标悬停在破折号上,下划线会出现在a 下方。

在搜索如何防止这种情况发生时,我遇到了this stackoverflow question。连同指针事件属性上的documentation on developer.mozilla.orgcaniusethis page,我确信这会解决它。但它没有。

我在这里错过了什么?

【问题讨论】:

    标签: css


    【解决方案1】:

    您需要在css中进行更改

    .wrap a::before {
        content: '----';
        padding: 0 15px;
        position: absolute;
        left: -50px;
        pointer-events: none;
    }
    .wrap a {
       text-decoration: none;
       position: relative;
       margin-left: 50px;
       display: inline-block;
    }
    

    【讨论】:

    • 啊,这是几分钟前发布的答案的更简洁版本。在这里更容易看到您提出的修改。谢谢:)
    • 谢谢 :) @Kablam
    【解决方案2】:

    您需要将position:absolute 用于---- 以使其脱离<a> 流,还需要将position:relative 用于父<a> 元素。

    堆栈片段

    .wrap a {
      text-decoration: none;
      margin: 0 30px;
      position: relative;
    }
    
    .wrap p {
      margin: 0;
    }
    
    .wrap {
      font-family: sans-serif;
      border: 1px solid green;
      padding: 5px;
      margin-bottom: 20px;
    }
    
    .wrap a:nth-of-type(1) {
      margin-left: 50px;
    }
    
    .wrap a::before {
      content: '----';
      position: absolute;
      pointer-events: none;
      left: -30px;
      transform: translateX(-50%);
    }
    
    .wrap a:hover {
      text-decoration: underline;
    }
    <div class="wrap">
      <p>These links do not have the pointer-events: none; property</p>
      <br>
      <a href="#">link text one</a>
      <a href="#">link text two</a>
      <a href="#">link text three</a>
    </div>
    
    <div class="wrap">
      <p>These do have pointer-events: none; yet their behaviour is the same as with the block above.</p>
      <br>
      <a href="#" class="pointerevents">link text one</a>
      <a href="#" class="pointerevents">link text two</a>
      <a href="#" class="pointerevents">link text three</a>
    </div>

    【讨论】:

    • 是的,我明白了!这很有效,但是它也涉及很多设置边距和头寸。我现在就这样实现它,但我仍然希望找出为什么 pointer-events: none; 没有按照我的预期去做。
    • @Kablam 如果你使用pointer-events:none 而不使用position:absolute,它将什么都不做,因为:before&lt;a&gt; 内,因此&lt;a&gt; 的总宽度将是inner-text+:before... .using position:absolute 使元素脱离流程,&lt;a&gt;width 将是唯一的内部文本 width,在这种情况下 pointer-events:none 将起作用
    • 谢谢!很好的解释!
    猜你喜欢
    • 2013-05-16
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 2022-12-18
    • 2020-11-29
    • 2012-12-16
    相关资源
    最近更新 更多