我使用以下代码获取相对于元素的选择的开始和结束位置:
function getSelectionCharOffsetsWithin(element) {
var start = 0, end = 0;
var sel, range, priorRange;
if (typeof window.getSelection != "undefined") {
range = window.getSelection().getRangeAt(0);
priorRange = range.cloneRange();
priorRange.selectNodeContents(element);
priorRange.setEnd(range.startContainer, range.startOffset);
start = priorRange.toString().length;
end = start + range.toString().length;
} else if (typeof document.selection != "undefined" &&
(sel = document.selection).type != "Control") {
range = sel.createRange();
priorRange = document.body.createTextRange();
priorRange.moveToElementText(element);
priorRange.setEndPoint("EndToStart", range);
start = priorRange.text.length;
end = start + range.text.length;
}
return {
start: start,
end: end
};
}
如何使用开始和结束位置更改该选择的css属性?,例如:
var data-start = data.start;
var data-end = data.end;
$('#document').css('background-color', 'blue'); //// but I only want to affect the selection I did before.
注意:我从mysql中检索开始和结束位置。
我需要这样的事情:http://jsfiddle.net/KcX6A/3534/ 但是元素必须是div
而不是输入