我已经实现了将选定文本包装在标签中的功能。您可以尝试单击“应用样式”按钮。
而且我还实现了删除标签的功能。
我想在删除标签时保持选中的文本,但我不知道如何实现它。
我已经在以下代码上尝试过,但它不起作用......
我在 Chrome 上运行此代码。
http://youtube.com/watch?v=VtBSJzoTmys&feature=youtu.be
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<link href="css/demo.css" rel="stylesheet" type="text/css">
<title></title>
</head>
<body>
<div id="buttons">
<input id="applyStyle" type="button" value="Apply Style" />
<input id="removeStyle" type="button" value="Remove Style" />
</div>
<div contenteditable="true">hello world</div>
</body>
</html>
main.js
$(function(){
var TextManager = function(){
var sel;
var naked;
};
TextManager.prototype = {
execCommand: function(commandWithArgs, valueArg){
var commandArr = commandWithArgs.split(' '),
command = commandArr.shift(),
args = commandArr.join(' ') + (valueArg || '');
document.execCommand(command, 0, args);
},
applyStyle: function(tagName, className){
this.sel = window.getSelection();
var snipet = '<' + tagName + ' class="' + className + '" >' + this.sel.toString() + '</' + tagName + '>';
this.execCommand('insertHTML', snipet);
console.log(this.sel);
this.sel.extend(this.sel.focusNode, 0);
},
removeStyle: function(){
var jcurnode = $(this.sel.focusNode.parentNode);
this.naked = jcurnode.text();
jcurnode.replaceWith(this.naked);
this.sel.extend(this.sel.focusNode, this.naked.length); //here, I'm trying to select text again which I removed the style.
},
};
textManager = new TextManager();
$('#applyStyle').on('click', function(){
textManager.applyStyle('div', 'testclass');
});
$('#removeStyle').on('click', function(){
textManager.removeStyle();
});
});
演示.css
div {
outline: none;
font-size: 20px;
font-family: 'Meiryo'
}
#buttons{
margin: 10px;
}
.testclass{
font-weight: bold;
}