JS貼り付け内容の取得
4433 ワード
http://classjs.com/2013/03/05/js%E8%8E%B7%E5%8F%96%E7%B2%98%E8%B4%B4%E5%86%85%E5%AE%B9/
構想:編集環境では、貼り付け時にカーソルのエディタ内の位置を記録し、空のdivを作成し、編集可能(contenteditable="true")に設定してカーソルをフォーカスさせます.フォーカスのテクニックはdiv.focus()です.このときカーソル貼り付け操作はさっき新しく作成したdivで、その内容は自然にこのdivにあります.settimeoutでdivの内容を取り出し、最後に貼り付け前の位置にカーソルを再配置して内容を挿入します.
ははは、このような考えはとても巧みですが、その中のテクニックはそんなに発見しやすいわけではありません.例えばdiv.focusとsettimeoutのテクニックですが、iframeモードでは無効でfocusのステップに引っかかっています.iframeのbodyはcontenteditable="true"環境、すなわちfocus状態であり、そのサブ要素もこのような状態にあるので、再びfocus()はできません.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
構想:編集環境では、貼り付け時にカーソルのエディタ内の位置を記録し、空のdivを作成し、編集可能(contenteditable="true")に設定してカーソルをフォーカスさせます.フォーカスのテクニックはdiv.focus()です.このときカーソル貼り付け操作はさっき新しく作成したdivで、その内容は自然にこのdivにあります.settimeoutでdivの内容を取り出し、最後に貼り付け前の位置にカーソルを再配置して内容を挿入します.
ははは、このような考えはとても巧みですが、その中のテクニックはそんなに発見しやすいわけではありません.例えばdiv.focusとsettimeoutのテクニックですが、iframeモードでは無効でfocusのステップに引っかかっています.iframeのbodyはcontenteditable="true"環境、すなわちfocus状態であり、そのサブ要素もこのような状態にあるので、再びfocus()はできません.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
onBeforePaste:
function
(target, e)
{
// ie , , ; 。
if
(__BROWSER.msie)
{
var
range = document.selection.createRange();
if
(range.text.length >0)
{
return
true
;
}
}
var
self =
this
;
//
target.style.position =
"static"
;
this
.saveScrollTop();
//
var
caretHolder = __addCaretHolder(target);
var
tmpDiv = document.createElement(
"div"
);
tmpDiv.contentEditable =
true
;
tmpDiv.style.position =
"absolute"
;
tmpDiv.style.top = caretHolder.offsetTop +
"px"
;
tmpDiv.style.left = caretHolder.offsetLeft +
"px"
;
tmpDiv.style.width =
"1px"
;
tmpDiv.style.height =
"1px"
;
tmpDiv.style.overflow =
"hidden"
;
this
.container.appendChild(tmpDiv);
tmpDiv.focus();
//
__setTimeoutEx(0,
function
(){
var
txt = tmpDiv.innerHTML;
caretHolder.innerHTML = txt;
__setCaret(caretHolder, -1);
__removeCaretHolder();
if
(tmpDiv.parentNode)
{
tmpDiv.parentNode.removeChild(tmpDiv);
}
// ,
target.style.position =
"relative"
;
self.restoreScrollTop();
});
return
true
;
},