mav*_*era 38 html javascript textarea selectedtext textselection
我有一个文本框和一个链接按钮.当我写一些文本,然后选择其中一些文本,然后单击链接按钮,文本框中的选定文本必须与消息框一起显示.
我该怎么做?
当我单击下面文本框的提交按钮时,消息框必须显示Lorem ipsum.因为在该地区选择了"Lorem ipsum".
如果我从页面中选择任何文本并单击提交按钮,它就可以正常工作,但如果我将文本写入文本框并进行创建,则不然.因为当我点击另一个空格时,文本框的选择被取消.
现在的问题是,当我从文本框中选择文本并单击任何其他控件或空格时,必须仍然选择所选文本.
怎么做?
Phi*_*Lho 39
好的,这是我的代码:
function ShowSelection()
{
var textComponent = document.getElementById('Editor');
var selectedText;
if (textComponent.selectionStart !== undefined)
{// Standards Compliant Version
var startPos = textComponent.selectionStart;
var endPos = textComponent.selectionEnd;
selectedText = textComponent.value.substring(startPos, endPos);
}
else if (document.selection !== undefined)
{// IE Version
textComponent.focus();
var sel = document.selection.createRange();
selectedText = sel.text;
}
alert("You selected: " + selectedText);
}
Run Code Online (Sandbox Code Playgroud)
问题,虽然我给IE的代码是在很多站点上给出的,但我无法在我当前系统上的IE6副本上运行.也许它会对你有用,这就是我给它的原因.
您寻找的技巧可能是.focus()调用,以回放textarea焦点,以便重新激活选择.
[UPDATE]我使用onKeyDown事件得到了正确的结果(选择内容):
document.onkeydown = function (e) { ShowSelection(); }
Run Code Online (Sandbox Code Playgroud)
所以代码是正确的.同样,问题是单击按钮进行选择......我继续搜索.
[更新]我用li标签绘制的按钮没有成功,因为当我们点击它时,IE会取消选择之前的选择.上面的代码使用一个简单的input按钮,但...
Dan*_*scu 17
这是一个更简单的解决方案,基于在mouseup上进行文本选择的事实,因此我们为此添加一个事件监听器:
document.querySelector('textarea').addEventListener('mouseup', function () {
window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
// window.getSelection().toString();
});Run Code Online (Sandbox Code Playgroud)
<textarea>
Select some text
</textarea>
<a href="#" onclick=alert(mySelection);>Click here to display the selected text</a>Run Code Online (Sandbox Code Playgroud)
这适用于所有浏览器.
如果您还想通过键盘处理选择keyup,请使用相同的代码添加另一个事件侦听器.
如果不是因为这个在2001年申请回Firefox的错误(是的,14年前),我们可以更换指定的值window.mySelection用window.getSelection().toString(),这在IE9 +以及所有现代浏览器上运行,并且还获得非textarea的部分所做的选择的DOM.