2014-02-11 34 views
0

我正在做一個文本編輯器,但刪除下劃線功能將不起作用。 工作的代碼示例: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

回答

1

很好用下劃線刪除的問題是,選擇並沒有考慮到包裝<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: -這僅僅是一個實驗。請在使用之前考慮性能/瀏覽器兼容性和其他利弊。

0

嘗試這樣:

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