我有一个小的降价编辑器
HTML:
<textarea id="txtarea">this is a **test**</textarea>
<button data-marker="**">Bold (toggle)</button>
<button data-marker="~~">Strike through (toggle)</button>
<button data-marker="*">Italics (toggle)</button>
JS:
function toggleMarker(marker, el) {
var markerLength = marker.length;
var startPos, endPos, selection, range;
if (document.selection != undefined) { // IE
el.focus();
range = document.selection.createRange();
selection = range.text;
} else if (el.selectionStart != undefined) { // Firefox
startPos = el.selectionStart;
endPos = el.selectionEnd;
selection = el.value.substring(startPos, endPos);
}
if (!selection.length){
return;
}
if (el.value.substring(startPos-markerLength,startPos) === marker
&& el.value.substring(endPos,endPos+markerLength) === marker
){
el.value = el.value.substring(0,startPos-markerLength) +
selection +
el.value.substring(endPos+markerLength);
}
else{
el.value = el.value.substring(0,startPos) + marker +
selection + marker + el.value.substring(endPos);
}
}
$(document).on('mousedown', 'button', function(e) {
toggleMarker( $(this).data('marker'), $('#txtarea').get(0) ).text;
});
现在我需要保持粘贴文本的突出显示。我怎么能这样做?
答案 0 :(得分:0)
http://codepen.io/medinasod/pen/GoOrwq
JS:
var markerLength,
startPos,
endPos,
selection,
range;
function selectText(startPos, endPos, markerLength, marker) {
mytxtarea = document.getElementById("txtarea");
window.setTimeout(function() {
if (mytxtarea.value.substring(startPos-markerLength,startPos) === marker && mytxtarea.value.substring(endPos,endPos+markerLength) === marker) {
mytxtarea.setSelectionRange(startPos+markerLength, endPos+markerLength);
} else {
mytxtarea.setSelectionRange(startPos+markerLength, endPos+markerLength);
}
}, 0);
}
function toggleMarker(marker, el) {
markerLength = marker.length;
if (document.selection != undefined) { // IE
el.focus();
range = document.selection.createRange();
selection = range.text;
} else if (el.selectionStart != undefined) { // Firefox
startPos = el.selectionStart;
endPos = el.selectionEnd;
selection = el.value.substring(startPos, endPos);
}
if (!selection.length){
return;
}
if (el.value.substring(startPos-markerLength,startPos) === marker
&& el.value.substring(endPos,endPos+markerLength) === marker
){
el.value = el.value.substring(0,startPos-markerLength) +
selection +
el.value.substring(endPos+markerLength);
}
else{
el.value = el.value.substring(0,startPos) + marker +
selection + marker + el.value.substring(endPos);
}
selectText(startPos, endPos, markerLength, marker);
}
$(document).on('mousedown', 'button', function(e) {
toggleMarker( $(this).data('marker'), document.getElementById('txtarea'));
});
HTML:
<textarea id="txtarea">this is a test</textarea>
<button data-marker="**">Bold (toggle)</button>
<button data-marker="~~">Strike through (toggle)</button>
<button data-marker="*">Italics (toggle)</button>