有許多弱點的時候文檔中得到選定的文本,大多與是否在表單控件中選擇文本或作爲其他元素的文本。嘗試執行如下功能:
function checkForSelectedText(e) {
var e = e || window.event;
var el = e.target || e.srcElement;
var tagName = el.tagName && el.tagName.toLowerCase();
var t;
var d = document;
// Try DOM 2 Range - for most browsers, including IE 6+
// However, doesn't get text selected inside form controls
// that allow selection of text content (input type text,
// textarea)
if (d && d.selection && d.selection.createRange) {
t = d.selection.createRange().text;
// Otherwise try HTML5 - note that getSelection returns
// a string with extra properties. This may also get
// text within input and textarea
} else if (d.getSelection) {
t = d.getSelection();
}
// If didn't get any text, see if event was inside
// [email protected]=text or textarea and look for text
if (t == '') {
if (tagName == 'textarea' ||
(tagName == 'input' && el.type == 'text')) {
// Check selectionStart/End as otherwise if no text
// selected, IE returns entire text of element
if (typeof el.selectionStart == 'number' &&
el.selectionStart != el.selectionEnd) {
t = el.value.substring(el.selectionStart, el.selectionEnd)
}
}
}
return t;
}
jQuery中的哪些方法可以做到這一點?無論如何,這應該是一個評論(除非改進)。 – Mrchief
選擇文本的最佳jquery函數:http://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse/987376#987376 – drharris
@drharris - 該功能使用瀏覽器嗅探,所以如果你使用瀏覽器以外的瀏覽器進行瀏覽,運氣不好。 – RobG