简体   繁体   English

如何镜像文本选择?

[英]How can I mirror text selection?

Say you have two inputs: 假设您有两个输入:

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

such that through some JavaScript magic, anything you type in input1 will also be put in input2. 这样,通过一些JavaScript魔术,您在input1中键入的任何内容也将被放入input2中。 In this sense input2 "mirrors" input1. 在这个意义上,输入2为“镜像”输入1。

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? 因此,如果我在input1中选择了一些文本,那么如何在input2中选择完全相同的文本呢?

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. 我一直在看Microsoft的TextRange对象和Mozilla等人使用的Selection对象,但是整个混乱似乎很麻烦。 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. 问题仅在于选择输入1中的文本,并选择输入2中的相应文本。

It's very easy in Firefox and Opera as far as I see. 据我所知,它在Firefox和Opera中非常简单。 Google Chrome and IE not so much. Google Chrome和IE没那么多。 Here's the code that works in FF: 这是在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: 如果可以使用JQuery ,则可以通过以下方式进行克隆:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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