日期:2014-05-16  浏览次数:20364 次

怎么获得鼠标选中的文字
在前台页面有一些文字,我用鼠标选中一些后,怎么能把这些文字自动放到<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>