2017-08-04 46 views
0

有人可以帮助我,如何将contenteditable div中的标记文本转换为btn上的大写或小写大小写点击jQuery?感谢您的回应。标记/选定/突出显示的文本大写或小写jQuery

<button type="button" id="asd" class="btn btn-info" onclick="replaceSelectedText(window.getSelection().toString().toUpperCase())">toUpper</button>

<script> 
function replaceSelectedText(replacementText) { 
    var sel, range; 
    if (window.getSelection) { 
     sel = window.getSelection(); 
     if (sel.rangeCount) { 
      range = sel.getRangeAt(0); 
      range.deleteContents(); 
      range.insertNode(document.createTextNode(replacementText)); 
     } 
    } else if (document.selection && document.selection.createRange) { 
     range = document.selection.createRange(); 
     range.text = replacementText; 
    } 
} 
</script> 
+0

标记怎么样?在你的文本字段? – xander

+2

你做了什么但尚未分享你的代码 –

+0

[阅读如何提出一个好问题](https://stackoverflow.com/help/how-to-ask)。 –

回答

0

您可以选择的文本内容编辑DIV为大写。检查此jsfiddle

[0] http://jsfiddle.net/jignesh221290/7kmb2fm2/ 

对于html标记,您必须管理。

1

你可以试试这个:

function replaceSelectedText(_this) { 
 
    
 
    var sel, range; 
 
    var selectedText=window.getSelection().toString(); 
 
    if ($.trim(selectedText)!="") { 
 
     sel = window.getSelection(); 
 
     
 
     if (sel.rangeCount) { 
 
      range = sel.getRangeAt(0); 
 
      range.deleteContents(); 
 
      if($(_this).html().toString().toUpperCase()=="TOUPPER"){ 
 
      range.insertNode(document.createTextNode(selectedText.toString().toUpperCase())); 
 
      $(_this).html("toLower"); 
 
      } 
 
      else{ 
 
      range.insertNode(document.createTextNode(selectedText.toString().toLowerCase())); 
 
      $(_this).html("toUpper"); 
 
      } 
 
     } 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p> 
 

 

 
<button type="button" id="asd" class="btn btn-info" onclick="replaceSelectedText(this)">toUpper</button>