使用JavaScript单击伪元素?

19

我想知道如何启用对:before伪元素的单击(下面链接的JSfiddle中div的橙色部分)。我已经阅读过由于伪元素不在DOM中,因此您需要一种方法来解决这个问题。不幸的是,我找不到一个现有的Stackoverflow Q&A能够展示可用的代码。

链接: http://jsfiddle.net/Vv6Eb/4/

HTML:

<div></div>

CSS:

div { position:relative; background-color:#333;
      padding:20px; margin:20px; float:left; 
}

div:before { content:""; display:block; 
    padding:5px; background-color:#f60; border:2px solid white; 
    position: absolute; top:-2px; right:-2px; border-bottom-left-radius: 10px; 
}

2
也许您可以提供更多关于您想要发生的事情的信息?可能有其他解决方法来实现预期的结果。 - James Montagne
2
你不能直接绑定到伪元素,但是你可以绑定到创建它的元素,点击伪元素将始终触发绑定到生成元素的事件。如果你必须只绑定到橙色部分,你需要创建一个新元素。 - BoltClock
@JamesMontagne,我只是想要能够像单击<a><button>一样单击伪元素。ComputerArts的建议对我有用,但你还有其他想法吗? - tim peterson
1
@timpeterson,我可能误解了你的意图。这个问题听起来好像你想在JavaScript中触发元素的点击。我想知道那有什么用处。现在我明白了,你实际上是想攻击一个点击处理程序。 - James Montagne
可能是仅在伪元素上检测点击事件的重复问题。 - Daut
6个回答

16

如果您知道圆形“应该”在哪里,您可以使用三角函数来判断点击是否在圆内:http://jsfiddle.net/Vv6Eb/19/

$("div").click(function(e){
    var $me = $(this),
        width = $me.outerWidth(),
        height = $me.outerHeight(),
        top = $me.position().top,
        left = $me.position().left;

    var len = Math.sqrt(Math.pow(width - e.offsetX, 2) + Math.pow(e.offsetY, 2));

    if (len < 10)
        alert('ding');
});​

不要使用 pow 函数来计算平方,而应该使用 * - Steven Lu

13
一个解决方法是动态地将<span>附加到该项上并为其分配一个点击方法。 像这个例子。
var item = $('<span />');
item.click(function() { alert('click'); });
$('div').append(item);
CSS
div { position:relative; background-color:#333;
      padding:20px; margin:20px; float:left;
}

div span { content:""; display:block;
    padding:5px; background-color:#f60; border:2px solid white;
    position: absolute; top:-2px; right:-2px; border-bottom-left-radius: 10px;
}

2
我知道你想使用:before,但对于这种情况,你是否可以创建一个带有类的新div用作钩子,并将其附加到原始div中?像这样的东西可能有效:
var newDiv = $("<div class='orangeCircle'>");
$(".parentDivToOrangeCircle").append(newDiv);

并且CSS:

.parentDivToOrangeCircle { position:relative; background-color:#333;
    padding:20px; margin:20px; float:left; 
}

.orangeCircle {
    padding:5px; background-color:#f60; border:2px solid white; 
    position: absolute; top:-2px; right:-2px; border-bottom-left-radius: 10px; 
}

@Jordan,我不需要使用:before。如果有其他方法,我非常感谢能看到代码是什么样子的。 - tim peterson

1

只需简单地使用jQuery

  $(document).on("click", "span", function(e){
         if (e.offsetX > $(this)[0].offsetWidth) {
               alert('clicked on after');
    } 
    else
    {
    alert('clicked on main span');
    }
        
    })
div { margin: 20px; }
span:after { content: 'AFTER'; position: absolute; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><span>ELEMENT</span></div>


0

在Medium上有一篇文章讲述了这个。

另外,这个CodePen链接

基本思路是追踪伪元素的位置。 下面的代码片段展示了一个没有边框半径的矩形的更一般情况,并在点击伪元素时关闭父元素。

const dismissable = document.querySelectorAll(".dismissable")

dismissable.forEach((d) => {
  d.addEventListener("click", (e)=>{
    // First we get the pseudo-elements style
    const target = e.currentTarget || e.target
    const after = getComputedStyle(target, ":after")
    if (after) {
      // Then we parse out the dimensions
      const atop = Number(after.getPropertyValue("top").slice(0, -2))
      const aheight = Number(after.getPropertyValue("height").slice(0, -2))
      const aleft = Number(after.getPropertyValue("left").slice(0, -2))
      const awidth = Number(after.getPropertyValue("width").slice(0, -2))
      // And get the mouse position
      const ex = e.layerX
      const ey = e.layerY
      // Finally we do a bounds check (Is the mouse inside of the after element)
      if (ex > aleft && ex < aleft+awidth && ey > atop && ey < atop+aheight) {
        console.log("Button clicked")
        target.style.display = "none"
      }
    }
  })
})
.dismissable {
  position: relative;
  width: 300px;
  height: 300px;
  border: 1px solid black;
  border-radius: 5px;
}

.dismissable:hover::after {
  content: "x";
  font-size: 3rem;
  display: block;
  position: absolute;
  top: 10px;
  left: 10px;
  cursor: pointer;
}
<div class="dismissable"></div>


0

我的目的已经通过另一种解决方法得到了解决,即添加一个子DIV。将父元素中的所有子元素都包裹在这个新的子DIV中:

我的工作示例与问题陈述相同:查看Fiddle

HTML:

<div class="parentDiv">
    :before
    <div class="childDiv">
        <!-- child elements -->
    </div>
</div>

**注意:在HTML中忽略:before,只是为了理解。

CSS:

div.parentDiv{position:relative; background-color:#333; padding:0; margin:20px; float:left; }
div.parentDiv:before { content:""; display:block; padding:5px; background-color:#f60; border:2px solid white; position: absolute; top:-2px; right:-2px; border-bottom-left-radius: 10px; cursor:pointer}

div.childDiv{padding:20px; margin:0}

jQuery:

jQuery(document).ready(function($){
    $('div.parentDiv').click(function(e){
        if( $(e.target).closest('.childDiv').length==0 ){
            //so clicked on psudo :before element!
            //do your work here ;)
            alert('Psudo :before element is clicked!');
        }
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接