简体   繁体   中英

How can I mirror text selection?

Say you have two inputs:

<input id="input1" type="text"/> and <input id="input2" type="text"/>

such that through some JavaScript magic, anything you type in input1 will also be put in input2. In this sense input2 "mirrors" input1.

Is there a way that I can also "mirror" text selection. So if I select some text in input1, how can I have the exact same text in input2 also be selected?

I've been looking at Microsoft's TextRange object and the Selection object used by Mozilla et al, but the whole mess seems pretty cumbersome. Has anyone had any success doing something like this before?

CLARIFICATION: Thanks for the responses so far. To be clear: I'm not asking how to mirror the text. I've already solved that one. The question is only about selecting the text in input1 and having the corresponding text in input2 also be selected.

It's very easy in Firefox and Opera as far as I see. Google Chrome and IE not so much. Here's the code that works in FF:

<!DOCTYPE html>

<html>
<head>
<meta charset="UTF-8">
</head>
<body>

<input type="text" size="40" id="sel-1" value="Some long text">
<input type="text" size="40" id="sel-2" value="Some long text">

<script type="text/javascript">
var sel_1 = document.getElementById("sel-1");
var sel_2 = document.getElementById("sel-2");

document.onmousemove = function () {
    sel_2.selectionStart = sel_1.selectionStart;
    sel_2.selectionEnd   = sel_1.selectionEnd;
}
</script>
</body>
</html>

您可以执行您要询问的第一部分(例如此处的答案),但是不能执行第二部分-一次不能选择一个以上的活动范围。

If you can live with using JQuery , then cloning can be done this way:

$("#input1").keyup(function() { 
  $("#input2").val( $("#input1").val() );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM