2016-09-09 1 views
2

나는 tinymce 플러그인을 사용하고 있습니다. & MS Word (shift + f3)와 같은 핫키에서 대문자 변경 기능을 수행하려고합니다.단축키로 대문자 변경 (MS-Word에서 Shift + F3과 같이)

선택 항목을 사용하여 관리했지만 단어가 선택되지 않은 경우에도 MS Word가 작동합니다.

커서의 현재 위치가 해당 위치의 단어로 분리되어 해당 단어에 기능을 적용합니다. 나는 tinymce를 위해 같은 것을 필요로한다.

지금까지 나는이 있습니다

editor.addShortcut("ctrl+e", "ll", function() { 
    var sel = editor.dom.decode(editor.selection.getContent()); 
    if (/^[a-zа-я]+$/g.test(sel)) { 
     sel = sel.substr(0, 1).toUpperCase() + sel.substr(1); 
    } 
    else if (/^[А-ЯA-Z]+$/g.test(sel)) { 
     sel = sel.toLowerCase(); 
    } 
    else { 
     sel = sel.toUpperCase(); 
    } 
    editor.selection.setContent(sel); 
    console.log(editor.selection); 
    editor.save(); 
    editor.isNotDirty = true; 
}); 

답변

1

다음 코드는 당신에게 당신이 원하는 결과를 제공 할 수 있습니다. 그것은 이러한 상황에서 작동해야합니다

  • 하나 이상의 단어가 완전히
  • 을 선택
  • 하나 이상의 단어가 부분적으로 선택
  • 어떤 텍스트가 선택된 텍스트가 속한
  • 선택하지
  • 이상의 단락
  • 다양한 텍스트 속성은 단어 안에 설정되어
tinymce.init({ 
    selector: "textarea", 
    plugins: [ 
     "advlist autolink lists link image charmap print preview anchor", 
     "searchreplace visualblocks code fullscreen", 
     "insertdatetime media table contextmenu paste" 
    ], 
    toolbar: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image", 
    setup: function (editor) { 

     editor.addShortcut("ctrl+e", "ll", function() { 

      var isWordChar = function (chr) { 
       return /\w/.test(chr); 
      }; 

      var isTextNode = function (node) { 
       return node.nodeType == 3; 
      }; 

      var getAllTextNodes = function (result, node) { 
       if (isTextNode(node)) { 
        result.push(node); 
       } 
       else if (node.childNodes) { 
        if (node.tagName == 'P') { 
         result.push(node); 
        } 
        var children = node.childNodes; 
        for (var i = 0; i < children.length; i++) { 
         getAllTextNodes(result, children[i]); 
        } 
       } 
       return result; 
      } 

      // Get current selection parameters 
      var range = editor.selection.getRng(); 
      var isCollapsed = editor.selection.isCollapsed(); 
      var selStartChildNode = range.startContainer; 
      var selEndChildNode = range.endContainer; 
      var selStartOffset = range.startOffset; 
      var selEndOffset = range.endOffset; 

      // Retrieve all the text nodes in the editor 
      var textNodes = []; 
      getAllTextNodes(textNodes, editor.dom.getRoot()); 

      var selStartNodeIndex = textNodes.indexOf(selStartChildNode); 
      var selEndNodeIndex = textNodes.indexOf(selEndChildNode); 
      var wordStartNodeIndex, wordEndNodeIndex; 
      var wordStartOffset, wordEndOffset; 
      var wordTextContent = ''; 
      var found = false; 
      var node, chr, lastCharIndex; 
      var i, j; 

      // Find the start of the first selected word 
      for (i = selStartNodeIndex; i >= 0 && !found; i--) 
      { 
       node = textNodes[i]; 
       if (isTextNode(node)) { 
        wordStartNodeIndex = i; 
        lastCharIndex = node.textContent.length - 1; 
        wordStartOffset = Math.max(0, Math.min(lastCharIndex, node == selStartChildNode ? selStartOffset - 1 : lastCharIndex)); 
        for (; wordStartOffset >= 0; wordStartOffset--) { 
         chr = node.textContent[wordStartOffset]; 
         if (isWordChar(chr)) { 
          wordTextContent = chr + wordTextContent; 
         } else { 
          found = true; 
          break; 
         } 
        } 
       } else { 
        found = true; 
        break; 
       } 
      } 

      wordStartOffset = Math.max(0, wordStartOffset); 

      var endNodeFound = false; 
      var pastEndNode = false; 
      var isAfterSelection = false; 
      found = false; 

      // Find the end of the last selected word 
      for (i = selStartNodeIndex; i < textNodes.length && !found; i++) { 
       node = textNodes[i]; 
       pastEndNode = endNodeFound; 
       if (isTextNode(node)) { 
        wordEndNodeIndex = i; 
        wordEndOffset = Math.min(node == selStartChildNode ? selStartOffset : 0, node.textContent.length - 1); 
        endNodeFound = endNodeFound || node == selEndChildNode; 

        for (; wordEndOffset < node.textContent.length; wordEndOffset++) { 
         chr = node.textContent[wordEndOffset]; 
         isAfterSelection = pastEndNode || (endNodeFound && wordEndOffset >= selEndOffset - (isCollapsed ? 0 : 1)); 
         if (isWordChar(chr) || !isAfterSelection) { 
          wordTextContent = wordTextContent + chr; 
         } else { 
          found = true; 
          break; 
         } 
        } 
       } else if (pastEndNode) { 
        found = true; 
        break; 
       } 
      } 

      // Determine the case style to be applied 
      var caseMode = ''; 
      if (/^([a-z0-9]|\W)+$/g.test(wordTextContent)) { 
       caseMode = 'CapitalizeWords'; 
      } 
      else if (/^([A-Z0-9]|\W)+$/g.test(wordTextContent)) { 
       caseMode = 'LowerCase'; 
      } 
      else { 
       caseMode = 'UpperCase'; 
      } 

      var startCharIndex, endCharIndex, currentIsWordChar; 
      var prevIsWordChar = false; 
      var content = ''; 

      // Apply the new case style to the selected nodes 
      for (i = wordStartNodeIndex; i <= wordEndNodeIndex; i++) { 
       node = textNodes[i]; 
       if (isTextNode(node)) { 
        startCharIndex = (i == wordStartNodeIndex ? wordStartOffset : 0); 
        endCharIndex = (i == wordEndNodeIndex ? wordEndOffset : node.textContent.length); 
        content = node.textContent.substring(0, startCharIndex); 
        switch (caseMode) { 
         case 'CapitalizeWords': 
          for (j = startCharIndex; j < endCharIndex; j++) { 
           chr = node.textContent[j]; 
           currentIsWordChar = /\w/.test(chr); 
           content += (currentIsWordChar && !prevIsWordChar ? chr.toUpperCase() : chr); 
           prevIsWordChar = currentIsWordChar; 
          } 
          break; 
         case 'LowerCase': 
          content += node.textContent.substring(startCharIndex, endCharIndex).toLowerCase(); 
          break; 
         case 'UpperCase': 
          content += node.textContent.substring(startCharIndex, endCharIndex).toUpperCase(); 
          break; 
        } 
        content += node.textContent.substring(endCharIndex); 
        node.textContent = content; 
       } else { 
        prevIsWordChar = false; 
       } 
      } 

      // Restore the selection range 
      range.setStart(selStartChildNode, selStartOffset); 
      range.setEnd(selEndChildNode, selEndOffset); 
      editor.selection.setRng(range); 

      editor.save(); 
      editor.isNotDirty = true; 
     }); 
    } 
}); 

this jsfiddle에서 사용해 볼 수 있습니다. 테스트를 단순화하기 위해 정규 표현식은 표준 미국 문자 만 고려합니다. 자신의 코드에 나타나는 특수 문자를 되돌릴 수 있습니다.

+0

이것은 정말 멋지 네요, 덕분에 도움을 많이 주셔서 감사합니다. – iamawebgeek

1
editor.selection.getRng().startOffset returns the cursor position 

출처 : https://drujoopress.wordpress.com/2014/08/06/find-cursor-position-inside-tinymce-editor/

바이올린 :
https://jsfiddle.net/16ssbdrn/

+0

예, 문서를 읽고 이러한 방법을 알고 있지만 문제를 해결하는 데 도움이되지 않습니다. – iamawebgeek

+0

커서 위치의 내용을 반복하여 단어의 시작과 끝을 찾을 수 있습니다. 그런 다음 변경 사항을 적용하십시오. 어떻게 든이 https://jsfiddle.net/16ssbdrn/1/ (공백 사이에서 단어를 찾는 것)과 같습니다. 그렇지 않으면 당신의 문제를 오해했을 수도 있습니다 – Focki