首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > JavaScript >

如何获得鼠标选中的文字

2012-04-18 
怎么获得鼠标选中的文字在前台页面有一些文字,我用鼠标选中一些后,怎么能把这些文字自动放到input type

怎么获得鼠标选中的文字
在前台页面有一些文字,我用鼠标选中一些后,怎么能把这些文字自动放到<input type="text">里面呢

还有怎么通过js获得我选择的文字呢

[解决办法]

JScript code
function getSelectionText(doc) {    if (!doc) doc = document;    var q;    try {        if (doc.parentWindow && doc.parentWindow.getSelection) q = doc.parentWindow.getSelection();        else if (doc.getSelection) q = doc.getSelection();        else if (doc.selection) q = doc.selection.createRange().text;    } catch(e) {}    if (!q) {        var iframes = doc.getElementsByTagName("iframe");        for (var i = 0; i < iframes.length; i++) {            try {                q = this.getSelectionText(iframes[i].contentWindow.document);            } catch(e) {}            if (q) return q;        }    }    return q;}
[解决办法]
<script>
function Test() {
 
try {
var selecter = window.getSelection();
 
if (selecter != null) {
alert(selecter);
}
} catch (err) {
var selecter = document.selection.createRange();
var s = selecter.text;
if (s != null && s.trim() != "") {
alert(s)
}
}
}
 
String.prototype.trim = function() {
return this.replace(/(^\s*)|(\s*$)/g, "");
}
 </script>

热点排行