演示:http: //jsfiddle.net/BGKSN/24/
$(document).ready(function(){
$('.format').click(function(){
var highlight = window.getSelection();
var spn = '<span class="highlight">' + highlight + '</span>';
var text = $('.conttext').text();
$('.conttext').html(text.replace(highlight, spn));
});
});
稍后编辑:
根据评论,这是真正的功能示例:
http://jsfiddle.net/BGKSN/40/
$(document).ready(function(){
$('.format').click(function(){
var highlight = window.getSelection(),
spn = '<span class="highlight">' + highlight + '</span>',
text = $('.conttext').text(),
range = highlight.getRangeAt(0),
startText = text.substring(0, range.startOffset),
endText = text.substring(range.endOffset, text.length);
$('.conttext').html(startText + spn + endText);
});
});
文档:https ://developer.mozilla.org/en-US/docs/Web/API/window.getSelection