顽固的下划线不会工作

问题描述:

我正在做一个文本编辑器,但删除下划线功能将不起作用。 工作的代码示例:jsfiddle顽固的下划线不会工作

这里是给人的问题

else if (tag == "u") { 
    sell = window.getSelection().getRangeAt(0); 

    if (selectionIsUnderlined()) { 
     node = range.createContextualFragment("<font style='text-decoration: none !important'>" + sell + "</font>"); 
    } else { 
     node = range.createContextualFragment("<u>" + sell + "</u>"); 
    } 

    range.deleteContents(); 
} 

任何想法的代码?

+0

代码给出了什么问题? – Muath

+0

如果我按下“U”按钮,选定的代码会被加下划线。如果我再次按下“U”按钮,它会检测带下划线的代码。那么它应该删除下属但是不起作用 – Arnout

+1

可能与'createContextualFragment'是一个实验性规范。 https://developer.mozilla.org/en-US/docs/Web/API/range.createContextualFragment – Andy

很好用下划线删除的问题是,选择并没有考虑到包装<u>元素。 <u>中的内容已被删除,并且<font>标签中插入了<u>标签内的新内容。

我试图去了一个节点,检查它是否是<u>,然后删除该节点:

if (selectionIsUnderlined()) { 
    node = range.createContextualFragment(
      "<font style='text-decoration: none !important'>" + sell + "</font>"); 
    var nd = sel.anchorNode; 
    if(nd.nodeName!=='span'){ 
     nd = nd.parentNode; 
    } 

    if (nd) { 
     nd.remove(); 
    } 

更新的小提琴是here

PS: -这仅仅是一个实验。请在使用之前考虑性能/浏览器兼容性和其他利弊。

尝试这样:

var node=""; 
var divs=0; 

if (selectionIsUnderlined()) { 
    node+="<div class=underline>"; 
    divs++; 
} 

if(selectionIsBold()){ 
    node+="<div class=bold>"; 
    divs++; 
} 

node+=sell; 

然后闭上你的div。

.underline{ 
    text-decoration: underline; 
} 

等。

+0

我试过了,但没有成功:/ – Arnout

+0

您是否尝试用jQuery/JS更改样式? – user3290463

+0

是的,我已经尝试过。 – Arnout