防止双击后选择文本

发布于 2024-07-20 05:40:42 字数 87 浏览 6 评论 0原文

我正在我的网络应用程序中的跨度上处理 dblclick 事件。 双击的副作用是它会选择页面上的文本。 我怎样才能防止这种选择发生?

I'm handling the dblclick event on a span in my web app. A side effect of a double click is that it selects text on the page. How can I prevent this selection from happening?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

草莓酥 2024-07-27 05:40:43

阻止 IE 8 CTRL 和 SHIFT 单击单个元素上的文本选择

var obj = document.createElement("DIV");
obj.onselectstart = function(){
  return false;
}

阻止文档上的文本选择

window.onload = function(){
  document.onselectstart = function(){
    return false;
  }
}

To prevent IE 8 CTRL and SHIFT click text selection on individual element

var obj = document.createElement("DIV");
obj.onselectstart = function(){
  return false;
}

To prevent text selection on document

window.onload = function(){
  document.onselectstart = function(){
    return false;
  }
}
小镇女孩 2024-07-27 05:40:43

旧线程,但我想出了一个我认为更干净的解决方案,因为它不会禁用绑定到对象的每个偶数,而只会阻止页面上的随机和不需要的文本选择。 它很简单,对我来说效果很好。
这是一个例子; 当我多次单击“arrow-right”类的对象时,我想阻止文本选择:

$(".arrow-right").hover(function(){$('body').css({userSelect: "none"});}, function(){$('body').css({userSelect: "auto"});});

HTH!

Old thread, but I came up with a solution that I believe is cleaner since it does not disable every even bound to the object, and only prevent random and unwanted text selections on the page. It is straightforward, and works well for me.
Here is an example; I want to prevent text-selection when I click several time on the object with the class "arrow-right":

$(".arrow-right").hover(function(){$('body').css({userSelect: "none"});}, function(){$('body').css({userSelect: "auto"});});

HTH !

吐个泡泡 2024-07-27 05:40:43

我知道这是一个老问题,但在 2021 年仍然完全有效。但是,我在答案方面缺少的是任何提及 Event.stopPropagation()

OP 要求使用 dblclick 事件,但据我所知,pointerdown 事件也出现同样的问题。 在我的代码中,我注册了一个侦听器,如下所示:

this.addEventListener("pointerdown", this._pointerDownHandler.bind(this));

侦听器代码如下所示:

_pointerDownHandler(event) {
  // Stuff that needs to be done whenever a click occurs on the element
}

在我的元素上快速单击多次会被浏览器解释为双击。 根据元素在页面上的位置,双击将选择文本,因为这是给定的行为。

可以通过调用 Event.preventDefault() 在监听器中,它确实解决了问题,至少在某种程度上是这样。

但是,如果您在元素上注册侦听器并编写相应的“处理”代码,您可能会吞掉该事件,这正是 Event.stopPropagation() 确保的。 因此,处理程序将如下所示:

_pointerDownHandler(event) {
  event.stopPropagation();
  // Stuff that needs to be done whenever a click occurs on the element
}

因为该事件已被我的元素消耗,所以层次结构中更靠上的元素不知道该事件,也不会执行其处理代码。

如果让事件冒泡,层次结构中较高的元素全部执行其处理代码,但被 Event.preventDefault() 告知不要这样做,这使得更少对我来说,这比从一开始就阻止事件发生更有意义。

I know this is an old question but it is still perfectly valid in 2021. However, what I'm missing in terms of answers is any mentioning of Event.stopPropagation().

The OP is asking for the dblclick event but from what I see the same problem occurs with the pointerdown event. In my code I register a listener as follows:

this.addEventListener("pointerdown", this._pointerDownHandler.bind(this));

The listener code looks as follows:

_pointerDownHandler(event) {
  // Stuff that needs to be done whenever a click occurs on the element
}

Clicking fast multiple times on my element gets interpreted by the browser as double click. Depending on where your element is located on the page that double click will select text because that is the given behavior.

You could disable that default action by invoking Event.preventDefault() in the listener which does solve the problem, at least in a way.

However, if you register a listener on an element and write the corresponding "handling" code you might as well swallow that event which is what Event.stopPropagation() ensures. Therefore, the handler would look as follows:

_pointerDownHandler(event) {
  event.stopPropagation();
  // Stuff that needs to be done whenever a click occurs on the element
}

Because the event has been consumed by my element, elements further up the hierarchy are not aware of that event and won't execute their handling code.

If you let the event bubble up, elements higher in the hierarchy would all execute their handling code but are be told to not do so by Event.preventDefault() which makes less sense to me than preventing the event from bubbling up in the first place.

满身野味 2024-07-27 05:40:43

顺风CSS:

<div class="select-none ...">
  This text is not selectable
</div>

Tailwind CSS:

<div class="select-none ...">
  This text is not selectable
</div>
绝情姑娘 2024-07-27 05:40:43

I had the same problem. I solved it by switching to <a> and add onclick="return false;" (so that clicking on it won't add a new entry to browser history).

风月客 2024-07-27 05:40:42
function clearSelection() {
    if(document.selection && document.selection.empty) {
        document.selection.empty();
    } else if(window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
    }
}

您还可以将这些样式应用于所有非 IE 浏览器和 IE10 的范围:

span.no_selection {
    user-select: none; /* standard syntax */
    -webkit-user-select: none; /* webkit (safari, chrome) browsers */
    -moz-user-select: none; /* mozilla browsers */
    -khtml-user-select: none; /* webkit (konqueror) browsers */
    -ms-user-select: none; /* IE10+ */
}
function clearSelection() {
    if(document.selection && document.selection.empty) {
        document.selection.empty();
    } else if(window.getSelection) {
        var sel = window.getSelection();
        sel.removeAllRanges();
    }
}

You can also apply these styles to the span for all non-IE browsers and IE10:

span.no_selection {
    user-select: none; /* standard syntax */
    -webkit-user-select: none; /* webkit (safari, chrome) browsers */
    -moz-user-select: none; /* mozilla browsers */
    -khtml-user-select: none; /* webkit (konqueror) browsers */
    -ms-user-select: none; /* IE10+ */
}
儭儭莪哋寶赑 2024-07-27 05:40:42

要防止仅在双击后选择文本:

您可以使用 MouseEvent#detail 属性。
对于 mousedownmouseup 事件,它是 1 加当前点击计数。

document.addEventListener('mousedown', function(event) {
  if (event.detail > 1) {
    event.preventDefault();
    // of course, you still do not know what you prevent here...
    // You could also check event.ctrlKey/event.shiftKey/event.altKey
    // to not prevent something useful.
  }
}, false);
Some dummy text

请参阅 https://developer.mozilla.org/en-US/文档/Web/API/UIEvent/detail

To prevent text selection ONLY after a double click:

You could use MouseEvent#detail property.
For mousedown or mouseup events, it is 1 plus the current click count.

document.addEventListener('mousedown', function(event) {
  if (event.detail > 1) {
    event.preventDefault();
    // of course, you still do not know what you prevent here...
    // You could also check event.ctrlKey/event.shiftKey/event.altKey
    // to not prevent something useful.
  }
}, false);
Some dummy text

See https://developer.mozilla.org/en-US/docs/Web/API/UIEvent/detail

帅冕 2024-07-27 05:40:42

在纯 javascript 中:

element.addEventListener('mousedown', function(e){ e.preventDefault(); }, false);

或使用 jQuery:

jQuery(element).mousedown(function(e){ e.preventDefault(); });

In plain javascript:

element.addEventListener('mousedown', function(e){ e.preventDefault(); }, false);

Or with jQuery:

jQuery(element).mousedown(function(e){ e.preventDefault(); });
別甾虛僞 2024-07-27 05:40:42

FWIW,我将 user-select: none 设置为那些我不希望在双击父元素上的任意位置时以某种方式选择的子元素的父元素。 它有效! 很酷的事情是 contenteditable="true",文本选择等仍然适用于子元素!

所以就像:

<div style="user-select: none">
  <p>haha</p>
  <p>haha</p>
  <p>haha</p>
  <p>haha</p>
</div>

FWIW, I set user-select: none to the parent element of those child elements that I don't want somehow selected when double clicking anywhere on the parent element. And it works! Cool thing is contenteditable="true", text selection and etc. still works on the child elements!

So like:

<div style="user-select: none">
  <p>haha</p>
  <p>haha</p>
  <p>haha</p>
  <p>haha</p>
</div>
谁人与我共长歌 2024-07-27 05:40:42

一个简单的 Javascript 函数,使页面元素内的内容不可选择:

function makeUnselectable(elem) {
  if (typeof(elem) == 'string')
    elem = document.getElementById(elem);
  if (elem) {
    elem.onselectstart = function() { return false; };
    elem.style.MozUserSelect = "none";
    elem.style.KhtmlUserSelect = "none";
    elem.unselectable = "on";
  }
}

A simple Javascript function that makes the content inside a page-element unselectable:

function makeUnselectable(elem) {
  if (typeof(elem) == 'string')
    elem = document.getElementById(elem);
  if (elem) {
    elem.onselectstart = function() { return false; };
    elem.style.MozUserSelect = "none";
    elem.style.KhtmlUserSelect = "none";
    elem.unselectable = "on";
  }
}
很酷不放纵 2024-07-27 05:40:42

对于那些正在寻找 Angular 2+ 解决方案的人。

您可以使用表格单元格的mousedown输出。

<td *ngFor="..."
    (mousedown)="onMouseDown($event)"
    (dblclick) ="onDblClick($event)">
  ...
</td>

并防止detail > 1..

public onMouseDown(mouseEvent: MouseEvent) {
  // prevent text selection for dbl clicks.
  if (mouseEvent.detail > 1) mouseEvent.preventDefault();
}

public onDblClick(mouseEvent: MouseEvent) {
 // todo: do what you really want to do ...
}

dblclick 输出继续按预期工作。

For those looking for a solution for Angular 2+.

You can use the mousedown output of the table cell.

<td *ngFor="..."
    (mousedown)="onMouseDown($event)"
    (dblclick) ="onDblClick($event)">
  ...
</td>

And prevent if the detail > 1.

public onMouseDown(mouseEvent: MouseEvent) {
  // prevent text selection for dbl clicks.
  if (mouseEvent.detail > 1) mouseEvent.preventDefault();
}

public onDblClick(mouseEvent: MouseEvent) {
 // todo: do what you really want to do ...
}

The dblclick output continues to work as expected.

好听的两个字的网名 2024-07-27 05:40:42

如果您试图完全阻止通过任何方法以及仅双击来选择文本,则可以使用 user-select: none css 属性。 我已经在 Chrome 68 中进行了测试,但根据 https://caniuse.com/#search=user-select 它应该可以在其他当前普通用户浏览器中工作。

从行为上来说,在 Chrome 68 中,它由子元素继承,并且不允许选择元素包含的文本,即使选择了围绕并包含该元素的文本也是如此。

If you are trying to completely prevent selecting text by any method as well as on a double click only, you can use the user-select: none css attribute. I have tested in Chrome 68, but according to https://caniuse.com/#search=user-select it should work in the other current normal user browsers.

Behaviorally, in Chrome 68 it is inherited by child elements, and did not allow selecting an element's contained text even if when text surrounding and including the element was selected.

甲如呢乙后呢 2024-07-27 05:40:42

如果您使用的是 Vue JS,只需将 @mousedown.prevent="" 附加到您的元素中,它就会神奇地消失!

If you are using Vue JS, just append @mousedown.prevent="" to your element and it is magically going to disappear !

东风软 2024-07-27 05:40:42

或者,在 mozilla 上:

document.body.onselectstart = function() { return false; } // Or any html object

在 IE 上,

document.body.onmousedown = function() { return false; } // valid for any html object as well

or, on mozilla:

document.body.onselectstart = function() { return false; } // Or any html object

On IE,

document.body.onmousedown = function() { return false; } // valid for any html object as well
誰ツ都不明白 2024-07-27 05:40:42

CSS 就足够了:

<style>
    #noselect{user-select: none;}
</style>
<div id="noselect"> NON SELECTABLE </div>

CSS is enough :

<style>
    #noselect{user-select: none;}
</style>
<div id="noselect"> NON SELECTABLE </div>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文