仅针对特定元素的JavaScript selectionchange事件 [英] JavaScript selectionchange event for a particular element only

查看:215
本文介绍了仅针对特定元素的JavaScript selectionchange事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在特定的div元素上实现JavaScrit selectionchange事件,因此,如果用户从DOM中选择文本,我想显示一个荧光笔框.我已经通过onmouseup事件在Web上实现了此功能.但是我一直坚持尝试在移动设备上实现这一点.

I want to implement a JavaScrit selectionchange event on a particular div element, so if the user selects text from the DOM I want to show a highlighter box. I have implemented this for web with an onmouseup event. But I am stuck trying to implement this for mobile devices.

对于移动浏览器,我在DOM上绑定了document.selectionchange事件,但是我希望这仅适用于具有content-editable类的特定元素.因此,仅当用户在页面上具有content-editable类的容器中选择文本时,荧光笔才会显示.

For mobile browsers I am binding document.selectionchange event on the DOM, but I want this to only apply for a particular element which has the content-editable class. So the highlighter will show only when the user selected text within the container on page which has the content-editable class.

document.addEventListener("selectionchange", function(evt) { 
  // Now this functionality only apply for content-editable class div.
});

如何实现此功能?也许可以使用递归函数来实现,以找到所选文本的anchorNodeanchorNode,例如:

How can I implement this functionality? Perhaps it could be implemented with a recursive function to find parentElement's class of anchorNode of selected text like:

var selection = ctrl.window.getSelection();

做到这一点的最佳方法是什么?

What is the best way to do this?

推荐答案

收听 selectstart 事件.仅在触发此事件时获得选择.

Listen for the selectstart event of your target element instead. Only get the selection when this event is fired.

const targetDiv = document.getElementById("interestingDiv");
function logSelection() {  
  console.log(document.getSelection().toString());
}
targetDiv.addEventListener("selectstart", () => {
  console.log("Selection started in targetDiv");
  document.addEventListener("selectionchange", logSelection);
});

selectstart事件在做出新选择后立即触发,因此一旦完成选择,您将需要某种方式来获取选择.我们可以听selectionchange,用某种方法在选择之后停止听.一种选择是停止在mouseleave上监听:

The selectstart event fires as soon as a new selection is made, so you will need some way to get the selection once it's complete. We can listen to selectionchange, with some way to stop listening after the selection is made. One option is to stop listening on mouseleave:

targetDiv.addEventListener("mouseleave", () => {
 document.removeEventListener("selectionchange", logSelection);
})

这篇关于仅针对特定元素的JavaScript selectionchange事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆