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

时间:2014-11-02 03:24:14

标签: ace-editor

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

一旦打字就会消失。

2 个答案:

答案 0 :(得分:14)

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

var editor = ace.edit("editor")

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_invisible ace_emptyMessage"
        node.style.padding = "0 9px"
        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>

答案 1 :(得分:0)

您可以使用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