如何在codemirror文本编辑器中使用onchange、onmouseup事件

问题描述 投票:0回答:2

我正在使用我的文本编辑器作为代码镜像。通常,当我尝试在文本区域中使用像

onmouseup, onchange, oninput
这样的dom事件时,它可以工作,但是在集成codemirror之后,它不起作用。请告诉我在文本编辑器中调用这些事件的正确方法。

无需codemirror,它也能工作。

<textarea id="editor" rows="30" cols="100" onchange="myFunction()" onmouseup="second();"></textarea>        
<div id="demo"></div>
<div id="second"></div> 
<script>
  function myFunction() {
       document.getElementById('demo').innerHTML="The onchange function..";}    
  function second() {
       document.getElementById('second').innerHTML="The mouseup function..";}
</script>       

在集成codemirror文本编辑器时,它不起作用。这是代码:

<textarea id="editor" onchange="myFunction()" onmouseup="second();"></textarea>
<div id="demo"></div>
<div id="second"></div> 
<script>
    var editor = CodeMirror.fromTextArea
    (document.getElementById('editor'),{
            mode:"text/x-java",
            lineNumbers:true,
            autoCloseTags:true,
            tabSize:5       
    });
    editor.setSize("1000", "450");              
    </script>       
    <script>
    function myFunction() {
          document.getElementById('demo').innerHTML="The onchange function..";}         
    function second() {
         document.getElementById('second').innerHTML="The mouseup function..";}

    </script>
javascript jquery textarea codemirror
2个回答
4
投票

因为这些事件实际上并没有发生在文本区域上,因为它是隐藏的,相反,您需要将事件绑定到

.CodeMirror
元素,如下所示:

$(document).on('mouseup', '.CodeMirror', function() {
    // do something...
});
$(document).on('change', '.CodeMirror', function() {
    // do something...
});

此外,我使用

keyup
而不是
change
事件,因为您必须单击
.CodeMirror
才能运行更改功能...


0
投票
var editor = CodeMirror.fromTextArea
   (document.getElementById('editor'),{
       mode:"text/x-java",
       lineNumbers:true,
       autoCloseTags:true,
       tabSize:5       
    });
    
editor.on('change', // change it your event
  (args) => {
  console.log("changes");
  console.log(args);
})
© www.soinside.com 2019 - 2024. All rights reserved.