試試這個
function SelectText(element) {
var doc = document;
var text = doc.getElementById(element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
$(function() {
$('.select').click(function() {
SelectText('selectme');
});
});
從https://stackoverflow.com/a/987376/1330581
獲得實施例http://jsfiddle.net/edelman/KcX6A/339/
更新:
選擇相同的點擊的元素的含量:
function SelectText(element) {
var doc = document;
var text = element;
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
$(function() {
$('.select').click(function() {
SelectText($(this)[0]); //Brackets are more efficiently that .get(0) method
});
});
的例子:http://jsfiddle.net/qBaWf/
這裏是沒有jquery的類似的問題:http://stackoverflow.com/questions/1173194/select-all-div單擊鼠標單擊 – lcoronelp 2012-07-17 01:33:56
[jQuery:選擇元素中的文本(類似於使用鼠標突出顯示)]的可能重複](http://stackoverflow.com/questions/985272/jquery-selecting-text-與鼠標突出顯示的元素相同) – 2012-07-17 01:54:35
所有鏈接的重複可能性僅爲ID選擇的元素提供解決方案。這個問題(和解決方案)用於突出顯示Class選定的項目。 – nipponese 2012-07-17 20:34:54