Problem:当使用setSelectionRange (在比内容更窄的输入字段中)以编程方式设置文本选择时,将选择所需的部分,但所选内容不会滚动到可见性中。似乎发生在镀铬和歌剧上。适用于Firefox和edge。
美国国家统计局( State: )称,自2014年以来,这实际上是一个众所周知的问题。因此,我主要感兴趣的是一个解决办法,因为这个问题会在我的应用程序中引起其他一些奇怪的副作用。
我已经试过暂停,额外的焦点-模糊对。
有以下输入的最小情况:
<input id="text" type="text" value="123456789" size="2"/>和下列职能:
function selectText() {
var input= document.getElementById("text");
input.focus();
setTimeout(function(){ //workaround for edge
input.setSelectionRange(7,9,"forward");
}, 1);
}这是要试用的代码。
发布于 2017-06-29 21:51:43
结合一些不同的技术,例如使用.focus()和将.scrollLeft设置为scrollWidth,您可以相对轻松地处理这个问题。下面的代码示例(基于提供的Fiddle )以及这个小屁孩中的代码示例。让我知道这是否如预期在所有浏览器(只测试Chrome)。
function selectText() {
var input = document.getElementById("text");
input.focus();
var txt = input.value;
setTimeout(function() {
document.getElementById("text").focus();
document.getElementById("text").scrollLeft = document.getElementById("text").scrollWidth;
document.getElementById("text").setSelectionRange(7, 9, "forward");
document.getElementById("selection").innerHTML = "selection is: " + txt.substring(input.selectionStart, input.selectionEnd);
}, 1);
}<p id="selection"></p>
<input id="text" type="text" value="123456789" size="2" />
<input type="button" value="Select" id="select" onclick="selectText()">
https://stackoverflow.com/questions/44835466
复制相似问题