codeBlock包裹在<pre>中,在按下Enter键时,在可内容的断点处。

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

在我的自定义编辑器中,将代码封装在了 <pre> 标签可以正常使用。我想用视觉化的方式组织粘贴的代码,以提高可读性。为此,我需要在代码块之间留出空行。但是,当我按下Enter键时,不是空行,而是整个代码块分成了两块,新的代码块用自己的前标签包装。下面的代码应该是在一个单块中,中间有一个空行 example_functionanother_example_function()

precode issue

顺便说一下జజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజజ contenteditable 类被设置为有 style="display:inline-block" 以防止 div.wrapper 在每一行上。可能的相关CSS信息 - pre { white-space: pre-wrap;}. 我在chrome 83.xx上。如果你需要更多信息,请告诉我。以下是我试过的,但失败了。

//there could be several code-blocks so running a loop to get all
let preTags = document.querySelector('.custom_editor').querySelectorAll('pre')
if (preTags) {
  preTags.forEach(function(item) { // attaching an event-listener to each code block
    item.addEventListener('click', function(e) {
      if (e.keyCode === 13) { //on enter just need a empty new line
        document.execCommand('insertHTML', false, '<br>');
        return false;
      }
    })
  }
}

HTML

<div class="content" style="display:inline-block;" contenteditable="true"></div>
javascript dom-events contenteditable execcommand
1个回答
0
投票

嵌套的预标签,例如 contenteditable>pre 这样的嵌套式预标签对于像 'keypress', 'keydown''keyup' 因为他们确实对我的这些事件做出了反应。该 'click' 的事件,但没有处理预标签中的 if (e.key === 'Enter') 检查,所以我没有遵循这个路线。

我没有为每个预标签监听事件,而是只为容器附加了一个监听器,突然间,我对enter-event的自定义设置在容器内和容器外的所有预标签中都起作用了。最终,我可以在按下Enter-event键时得到预标签内的空行。进入 钥匙。

document.querySelector('.custom_editor').addEventListener('keypress', someFunc)
function someFunc(e){
    if (e.key === 'Enter') { 
        document.execCommand('insertHTML', false, "<br>");
        e.preventDefault()
    } 
}
© www.soinside.com 2019 - 2024. All rights reserved.