通过 JS 更改 CodeMirror 占位符
Change CodeMirror Placeholder via JS
我正在使用 CodeMirror 5.51 版和占位符 addon。
占位符本身是这样设置的。
<textarea id="code" class="hidden" placeholder="Paste your XML here..."></textarea>
当用户现在更改网站的语言时,我也想更改占位符的文本。
我试过直接设置占位符
this.$editor.options.placeholder = "New value"
但这不会立即生效。
有没有办法
- 指定函数returns字符串而不是直接字符串?
- 通过函数调用重新初始化占位符?
插件的 code 建议您可以使用除字符串以外的其他内容,但我找不到关于该主题的更多信息。
您可以使用 cm.setOption()
方法以编程方式更新占位符文本,即:
this.$editor.setOption('placeholder', 'New value');
这是一个概念验证示例:
const editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true
});
document.getElementById('update-placeholder-text').addEventListener('click', () => {
editor.setOption('placeholder', document.getElementById('placeholder-text').value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/addon/display/placeholder.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.min.css" rel="stylesheet" />
<input type="text" id="placeholder-text" value="Lorem ipsum" /><button id="update-placeholder-text">Update placeholder text</button>
<hr />
<textarea id="code" name="code" placeholder="Code goes here..."></textarea>
经过一段时间的修补,我发现以下两行可以解决问题。
第一行在内部设置新值,而第二行(显然)覆盖当前的 UI 表示。
this.$editor.options.placeholder = "Value";
this.$editor.state.placeholder.innerText = "Value";
第一行(我假设)与@Terry 建议的相同。
this.$editor.setOptions('placeholder', 'New value');
我正在使用 CodeMirror 5.51 版和占位符 addon。 占位符本身是这样设置的。
<textarea id="code" class="hidden" placeholder="Paste your XML here..."></textarea>
当用户现在更改网站的语言时,我也想更改占位符的文本。
我试过直接设置占位符
this.$editor.options.placeholder = "New value"
但这不会立即生效。
有没有办法
- 指定函数returns字符串而不是直接字符串?
- 通过函数调用重新初始化占位符?
插件的 code 建议您可以使用除字符串以外的其他内容,但我找不到关于该主题的更多信息。
您可以使用 cm.setOption()
方法以编程方式更新占位符文本,即:
this.$editor.setOption('placeholder', 'New value');
这是一个概念验证示例:
const editor = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true
});
document.getElementById('update-placeholder-text').addEventListener('click', () => {
editor.setOption('placeholder', document.getElementById('placeholder-text').value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/addon/display/placeholder.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.54.0/codemirror.min.css" rel="stylesheet" />
<input type="text" id="placeholder-text" value="Lorem ipsum" /><button id="update-placeholder-text">Update placeholder text</button>
<hr />
<textarea id="code" name="code" placeholder="Code goes here..."></textarea>
经过一段时间的修补,我发现以下两行可以解决问题。
第一行在内部设置新值,而第二行(显然)覆盖当前的 UI 表示。
this.$editor.options.placeholder = "Value";
this.$editor.state.placeholder.innerText = "Value";
第一行(我假设)与@Terry 建议的相同。
this.$editor.setOptions('placeholder', 'New value');