我有一个普通的文本框和一个带有文本输入的灯箱。
我想将用户的选择保留在文本框中,即使用户将注意力集中在灯箱的文本输入上也是如此。
- 在普通文本框中选择文本
- 切换灯箱
- 专注于灯箱输入
在第 3 步,用户的文本选择被丢弃。如何预防?例如,请参阅 Google 文档链接插入灯箱。
谢谢:)
更新
好的,Google 文档对空白页面部分使用了 iframe,这就是他们处理多项选择的方式。像这样的东西(请原谅恶心的 HTML):
// test.html
<html><body>
<h1 onclick='lightbox();'>This is the main section</h1>
<iframe src='frame.html'></iframe>
<div id='lightbox' style='display: none; position: fixed; top: 0; left: 0; height: 100%; width: 100%; opacity: 0.8; background-color: black;'>
<input type='text' name='url' />
</div>
<script type='text/javascript'>
function lightbox() {
document.getElementById('lightbox').style.display = 'block';
}
</script>
</body></html>
// frame.html
<p>This is my iframe</p>
iframe 中的文本选择独立于 对灯箱中输入的焦点。因此,如果选择了一些文本“这是我的 iframe”,然后切换灯箱并将光标放置在输入中,则 iframe 的文本选择会持续存在,而无需任何 javascript。
我现在正在尝试 Nickolay 的建议。
最佳答案
来自 How to preserve text selection when opening a jQuery dialog : 你必须在模糊时保留选择并在聚焦时恢复它:
$("dialog").focus(function() {
// save the selection
}).blur(function() {
// set the text selection
});
设置选择(来自 jQuery Set Cursor Position in Text Area ):
$.fn.selectRange = function(start, end) {
return this.each(function() {
if(this.setSelectionRange) {
this.focus();
this.setSelectionRange(start, end);
} else if(this.createTextRange) {
var range = this.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
});
};
$('#elem').selectRange(3,5);
获取选择:http://laboratorium.0xab.cd/jquery/fieldselection/0.1.0/test.html
关于javascript - 焦点改变时保持文本选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1592637/