プログラム問答

初期の mousedown イベントの後のテキストの選択範囲をキャンセルする方法

 

クリック-と-持つに、ベースのポップアップ メニューを実装しようとしている遅い (本当に) をクリックに既定のアクションをトリガーしと遅延設定テキスト選択ジェスチャは通常、メニューをトリガーしませんので、まだように配置します。

行うにはキャンセル - 選択したテキストを最初の場所で防止しない方法でのテキスト選択できない: イベントハンドラーから false を返す (または呼び出す $(this).preventDefault() ) すべてを選択して明らかであることから、ユーザーを防ぎます $().trigger('mouseup') doesn't 選択と何もないです。

  • This is in the general context of a page, not particular to a textarea or other text field.
  • e.stopPropogation() doesn't cancel text-selection.
  • I'm not looking to prevent text selections, but rather to veto them after some short period of time, if certain conditions are met.
#1

これを試してください。

var input = document.getElementById('myInputField');
if (input) {
    input.onmousedown = function(e) {

	    if (!e) e = window.event;
	    e.cancelBubble = true;
	    if (e.stopPropagation) e.stopPropagation();

    }
}

いない場合は、読み取り。

http://www.quirksmode.org/js/introevents.html

#2

トップのスレッドに加えて、ある公式の方法は DOM でたいと思うを実装するにはイベントの代わりに何を使用するは、range オブジェクトと呼ばれるものです。

検討、(決定的に FF3 作品)

window.onclick = function(evt)
{
   // retrieves the selection and displays its content
   var selectObj = window.getSelection();
   alert(selectObj);

   // now collapse the selection to the initial point of the selection
   var rangeObj = selectObj.getRangeAt(0);
   rangeObj.collapse(true);
}

残念ながら、これはかなり IE、オペラ、クロムメッキ、または Safari を飛ぶことはない;オペラでは、クロム、またはサファリがあるので分からないなぜ、何か崩壊と getRangeAt メソッドが関連付け。詳細を知っている場合は、私はあなたを知ってもらいましょう。


私の前の答えを 1 つより普遍的に作品を更新、選択オブジェクトと崩壊、collapseToStart、collapseToEnd のメソッドです。(リンク テキスト)

今すぐ上記の 2.0 を考慮してください。


window.onmouseup = function(evt)
{
   var selectObj = window.getSelection();
   alert(selectObj); // to get a flavor of what you selected

   // works in FF3, Safari, Opera, and Chrome
   selectObj.collapseToStart();

   // works in FF3, Safari, Chrome (but not opera)
   /* selectObj.collapse(document.body, 0); */

   // and as the code is native, I have no idea why...
   // ...and it makes me sad
}

#3

よく分からない場合は、この正確には役立つだろうが、ここでいくつかのコード テキストを選択解除します:

// onselectstart is IE-only
if ('undefined' !== typeof this.onselectstart) {
    this.onselectstart = function () { return false; };
} else {
    this.onmousedown   = function () { return false; };
    this.onclick       = function () { return true;  };
}

「この」このコンテキストでは、要素のテキストの選択範囲を防止するでしょう。

#4

$(this).focus()(またはの線に沿って何か document.body.focus() )私は ff3 を超えてはるかにそれをテストしていないが、トリックを行うようです。

#5

この質問への答えは私の作品:Jquery を使用してテキストの選択を無効にする方法か。

無効に (それだけではなく、またにをキャンセル、任意のテキストの選択します。
At least コンピュータ上の FF とクローム)。

ここでは何の答え:

    .attr('unselectable', 'on')

    '-ms-user-select': 'none',
    '-moz-user-select': 'none',
    '-webkit-user-select': 'none',
    'user-select': 'none'

    .each(function() {  // for IE
      this.onselectstart = function() { return false; };
    });