Jak*_*old 30 javascript jquery
我正在尝试制作自己的WYSIWYG编辑器.有什么办法,如何获取用户在textarea中选择的文本?
例如,如果用户选择了某个单词然后单击按钮,我该如何找出选择了哪个文本?
我正在使用jQuery.
Hon*_*Abe 59
要在window.getSelection().toString()Firefox中获取所选内容:
function getSel() // javascript
{
// obtain the object reference for the <textarea>
var txtarea = document.getElementById("mytextarea");
// obtain the index of the first selected character
var start = txtarea.selectionStart;
// obtain the index of the last selected character
var finish = txtarea.selectionEnd;
// obtain the selected text
var sel = txtarea.value.substring(start, finish);
// do something with the selected content
}
Run Code Online (Sandbox Code Playgroud)
<textarea> 我使用Chrome而不是Firefox.
参考:
Sco*_*den 16
不同浏览器的处理选择是不同的:
var userSelection;
if (window.getSelection) {
userSelection = window.getSelection();
}
else if (document.selection) { // Opera
userSelection = document.selection.createRange();
}
Run Code Online (Sandbox Code Playgroud)
这会给你一个范围对象.每个范围代表一个选择(使用控制/命令键可以进行多个活动选择).
您现在拥有的范围对象的类型取决于浏览器.对于IE,它是一个Text Range对象; 对于其他人来说是一个Selection对象.要将Selection对象转换为文本范围,可以调用getRangeAt; 对于Safari,你需要构建:
var range;
if (userSelection.getRangeAt)
range = userSelection.getRangeAt(0);
else { // Safari
range = document.createRange();
range.setStart(userSelection .anchorNode, userSelection.anchorOffset);
range.setEnd(userSelection.focusNode, userSelection.focusOffset);
}
Run Code Online (Sandbox Code Playgroud)
范围对象为您提供选择的起始和结束dom元素以及文本偏移.
有关范围对象的更多信息,请访问quirksmode.org
如果您使用的是jQuery,您可能需要查看Batiste Bieler 的轻量级jQuery RTE插件.它可能足以满足您的需求,或者至少可以为您提供一些东西.
getSelection()
这有点不同浏览器,请参阅此处了解最多可以使用的功能:http: //snipplr.com/view/775/getselection/
一个小的函数,它将获取文本区域或输入元素的选定字符串/文本:
function getInputSelection(elem){
if(typeof elem != "undefined"){
s=elem[0].selectionStart;
e=elem[0].selectionEnd;
return elem.val().substring(s, e);
}else{
return '';
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,以上代码需要jQuery才能工作。获取ID为abc123的输入元素的选定字符串的示例
getInputSelection($("#abc123"));
Run Code Online (Sandbox Code Playgroud)
上面的函数将返回选择的字符串。如果没有用户选择的字符串,它将返回null。
getInputSelection($("body").find("input[name=user]"));
Run Code Online (Sandbox Code Playgroud)
在使用类名选择的元素上,将返回元素数组的第一个元素的选定字符串,而不是所有元素的选定字符串。毕竟,页面中的选择始终为1。
| 归档时间: |
|
| 查看次数: |
69843 次 |
| 最近记录: |