我正在开发一个所见即所得的编辑器,我无法撤消之前应用的效果。
示例:如果我选择一些文本并加粗,它可以正常工作。但是如果我想删除它的粗体效果,我无法将className应用于所选文本。 (JS中的第6行)在控制台中,我可以看到它实际存在于sel > anchorNode > nextElementSibling > className
下,但不确定为什么它不允许获取它。
function replaceSelectedText(className) {
var selectedText, sel, range;
if (window.getSelection) {
sel = window.getSelection();
// check if selection has a class
if(sel.anchorNode){
console.dir(sel);
if(sel.anchorNode.nextElementSibling){
console.log("className:" + sel.anchorNode.nextElementSibling.className);
}
}
selectedText = window.getSelection().toString();
//console.log(selectedText);
if (sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
var element = document.createElement('span');
element.className = className;
element.textContent = selectedText;
range.insertNode(element);
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.text = replacementText;
}
}
var toolbarButtons = document.querySelectorAll("#toolbar button");
//console.log(toolbarButtons);
for (var i = 0; i < toolbarButtons.length; ++i) {
toolbarButtons[i].addEventListener('click', function(){
replaceSelectedText(this.id);
console.log(document.getElementById("editable").innerHTML);
});
}
&#13;
#editable{
border: 1px solid #000000;
margin-top: 20px;
height: 50px;
font-family: Arial;
}
.bold{
font-weight: bold;
}
.italic{
font-style: italic;
}
&#13;
<div id="toolbar">
<button id="bold">Bold</button>
<button id="italic">Italic</button>
</div>
<div id="editable" contentEditable="true">
<div>Lorem Ipsum Lorem Ipsum</div>
</div>
&#13;
适用于Firefox,但不适用于Chrome。
如何在Chrome中获取className?
答案 0 :(得分:0)
似乎有针对Chrome和Firefox的个性化解决方案。
Firefox :sel.anchorNode.nextElementSibling.className
Chrome :sel.baseNode.parentElement.className
我通过检测浏览器修复了它。
检测浏览器:
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
var isFirefox = typeof InstallTrigger !== 'undefined'; // Firefox 1.0+
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
// At least Safari 3+: "[object HTMLElementConstructor]"
var isChrome = !!window.chrome && !isOpera; // Chrome 1+
var isIE = /*@cc_on!@*/false || !!document.documentMode; // At least IE6
JS条件:
if(isChrome){
if(sel.baseNode.parentElement.className){
console.log("isChrome className:" + sel.baseNode.parentElement.className);
sel.baseNode.parentElement.className = "";
return false;
}
}
if(isFirefox){
if(sel.anchorNode.nextElementSibling){
console.log("isFirefox className:" + sel.anchorNode.nextElementSibling.className);
sel.anchorNode.nextElementSibling.className = "";
return false;
}
}