15

以下のように bind paste イベントを使用できることはわかっています。

$('#id').bind('paste', function(e) { 
    alert('pasting!') 
});

しかし、問題は、貼り付けられたテキストの貼り付けの前に呼び出されることです。右クリック後に関数をトリガーしたい->入力フィールドに貼り付けられたテキストを貼り付けて、イベントハンドラー関数内の貼り付けられた値にアクセスできるようにします。

.change()イベントも役に立ちません。現在.keyup()、その入力フィールドに入力しているときに残りの文字数を表示する必要があるため、イベントを使用しています。

4

5 に答える 5

26

一種のハックですが、:

$("#id").bind('paste', function(e) {
        var ctl = $(this);
        setTimeout(function() {
            //Do whatever you want to $(ctl) here....
        }, 100);
});
于 2012-08-27T17:44:43.583 に答える
3

これにより、ユーザーはキーボードで貼り付け、対処、または切り取りを行うことができなくなります。

$("#myField").keydown(function(event) {
   var forbiddenKeys = new Array('c', 'x', 'v');
   var keyCode = (event.keyCode) ? event.keyCode : event.which;
   var isCtrl;
   isCtrl = event.ctrlKey

     if (isCtrl) {
       for (i = 0; i < forbiddenKeys.length; i++) {
           if (forbiddenKeys[i] == String.fromCharCode(keyCode).toLowerCase()) {
             return false;
        }
     }
}
return true;
});

これは、マウスイベントに対して同じことを行います:

$("#myField").bind("cut copy paste",function(event) {
   event.preventDefault();
});

上記のものは右クリックを妨げませんが、ユーザーはそのフィールドから貼り付け、切り取り、またはコピーすることはできません。

イベント後に使用するには、質問で疑問に思ったように、JavaScript Timing Eventを使用する必要があります

setTimeout(function() {
  // your code goes here
}, 10);
于 2012-08-27T18:07:48.337 に答える
0

私は同じ問題を抱えていました.javascriptを介して貼り付けアクションを複製し、代わりにその出力を使用することにしました:

var getPostPasteText = function (element, pastedData) {
    // get the highlighted text (if any) from the element
    var selection = getSelection(element);
    var selectionStart = selection.start;
    var selectionEnd = selection.end;

    // figure out what text is to the left and right of the highlighted text (if any)
    var oldText = $(element).val();
    var leftPiece = oldText.substr(0, selectionStart);
    var rightPiece = oldText.substr(selectionEnd, oldText.length);

    // compute what the new value of the element will be after the paste
    // note behavior of paste is to REPLACE any highlighted text
    return leftPiece + pastedData + rightPiece;
};

IE の document.selection.createRange には、関数のソースの先頭または末尾の空白行が含まれていませんgetSelection

于 2012-08-27T18:02:40.240 に答える