2013-11-03 67 views
2

我已經實現了在標籤中包裝選定文本的功能。您可以嘗試點擊「應用樣式」按鈕。
而且我已經實現了刪除標籤的功能。
我想保留標籤被刪除時選中的文本,但我不知道如何實現它。
我試了下面的代碼,但它不工作...
我在Chrome上運行此代碼。
如何選擇可替代區域上的替換文本

http://jsfiddle.net/f5HaK/3/

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(); 
    }); 

}); 

demo.css

div { 
    outline: none; 
    font-size: 20px; 
    font-family: 'Meiryo' 
} 

#buttons{ 
    margin: 10px; 
} 

.testclass{ 
    font-weight: bold; 
} 
+0

對不起,我忘了保存我的jsfiddle。我現在就救了它。 – Nigiri

+0

我的網頁瀏覽器是Chrome。 – Nigiri

+1

你的jsfiddle沒有任何javascript或css。 – hcoat

回答

1

,因爲您從DOM調用jcurnode.replaceWith(this.naked)當元素的文本不保持選中狀態;,刪除的節點不能保持選中狀態。 你可以通過這條線從removeStyle更換線

jcurnode.replaceWith(this.naked); 

修復:

this.execCommand('removeFormat', ""); 

或許,您希望看到所有的命令標識符的列表,可用於:http://help.dottoro.com/larpvnhw.php

+1

OMG!我認爲'removeFormat'只有在我用'execCommand'方法包裝文本時才起作用。謝謝 !! – Nigiri