【问题标题】:How can I add placeholder text when the editor is empty编辑器为空时如何添加占位符文本
【发布时间】:2014-11-02 03:24:14
【问题描述】:

编辑器为空时如何添加占位符文本?

一旦开始输入,它就会消失。

【问题讨论】:

    标签: ace-editor


    【解决方案1】:

    您可以为input 事件添加侦听器,并在需要时添加带有文本的 div,如下所示:

    var editor = ace.edit("editor", {
      theme: "ace/theme/chaos"
    })
    
    function update() {
        var shouldShow = !editor.session.getValue().length;
        var node = editor.renderer.emptyMessageNode;
        if (!shouldShow && node) {
            editor.renderer.scroller.removeChild(editor.renderer.emptyMessageNode);
            editor.renderer.emptyMessageNode = null;
        } else if (shouldShow && !node) {
            node = editor.renderer.emptyMessageNode = document.createElement("div");
            node.textContent = "placeholder"
            node.className = "ace_emptyMessage"
            node.style.padding = "0 9px"
            node.style.position = "absolute"
            node.style.zIndex = 9
            node.style.opacity = 0.5
            editor.renderer.scroller.appendChild(node);
        }
    }
    editor.on("input", update);
    setTimeout(update, 100);
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8">
      <title>JS Bin</title>
      <script src="http://ajaxorg.github.io/ace-builds/src/ace.js"></script> 
      <style>
        #editor { position: absolute; top: 0; left: 0; right: 0; bottom: 0;}
      </style>
    </head>
    <body>
     <div id="editor"></div> 
    </body>
    </html>

    【讨论】:

    • 如何为 angular4 添加它?
    • 您可以使用组件生命周期挂钩并相应地添加此逻辑,不是吗?
    • 这似乎适用于某些(但不是全部)ace 主题。例如,当从编辑器中删除 vnijs.shinyapps.io/shinyAce-01-basic 的“氛围”主题而不是“混乱”主题的文本时,会显示一个占位符。有什么建议吗?
    • 占位符在高亮行后面,更新了示例以处理这种情况
    • 现在有一个“占位符”选项
    【解决方案2】:

    您可以使用placeholder: "Your Placeholder Text" 选项将占位符放入您的 Ace 编辑器中。

    HTML 代码

    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/ace.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/mode-css.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.12/theme-cobalt.min.js"></script>
    
    <div id="editor"></div>
    

    CSS 代码:

    #editor { 
      position: relative;
      min-height: 100px;
    }
    

    JavaScript 代码

    var editor = ace.edit("editor");
    editor.setOptions({
      mode: 'ace/mode/css',
      theme: 'ace/theme/cobalt',
      placeholder: "Enter CSS Code",
    })
    

    Demo On CodePen

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 2016-08-29
      • 1970-01-01
      • 2018-11-27
      相关资源
      最近更新 更多