我正在尝试通过选择change
事件来更改代码镜像上的语言模式。
当我尝试使用select元素通过change
事件更改模式时,代码镜像会丢失其样式。
确实,正在发生的事情是删除具有某些类的span
标签,但是我不知道为什么。
如何在代码镜像上保留文本样式?
$(function() {
var widget = $('.widget');
var settings = widget.find('.widget-settings');
var editor = CodeMirror.fromTextArea(widget.find('.demotext')[0], {
mode: {
name: "javascript",
json: true
},
lineNumbers: true,
smartIndent: true,
indentWithTabs: true,
styleActiveLine: true,
matchBrackets: true
});
widget.find('.CodeMirror').attr('data-language', 'js');
var theme = 'pastel-on-dark';
editor.setOption("theme", theme);
location.hash = "#" + theme;
editor.save();
function mirrorSettings(editor) {
$(document).on('change', '.code-mode', function() {
var widget = $(this).closest('.widget');
var language = $(this).find(':selected').attr('data-lang');
console.log(language);
var theme = 'pastel-on-dark';
editor.setOption("mode", language);
editor.setOption("theme", theme);
switch (language) {
case 'HTML mixed-mode':
widget.find('.CodeMirror').attr('data-language', 'html');
break;
case 'JavaScript':
widget.find('.CodeMirror').attr('data-language', 'js');
break;
case 'CSS':
widget.find('.CodeMirror').attr('data-language', 'css');
break;
}
});
}
mirrorSettings(editor);
});
.widget {
width: 500px;
}
/* Lang: JavaScript */
[data-language='js'] .cm-keyword {
color: #ffcc99 !important;
}
[data-language='js'] .cm-def {
color: white !important;
}
[data-language='js'] .cm-variable-2,
[data-language='js'] .cm-variable {
color: #6a51e6 !important;
}
[data-language='js'] .cm-property {
color: #9b87fd !important;
}
[data-language='js'] .cm-string {
color: #ffba76 !important;
}
[data-language='js'] .cm-operator {
color: #ffba76 !important;
}
/* Lang: HTML */
[data-language='js'] .cm-keyword {
color: #ffcc99 !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://codemirror.net/lib/codemirror.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.40.0/mode/javascript/javascript.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.35.0/codemirror.css" />
<link rel="stylesheet" href="https://codemirror.net/theme/pastel-on-dark.css" />
<div class="widget" data-widget="code" style="">
<div class="widget-settings">
<select class="form-control form-control-sm code-mode">
<option data-lang="JavaScript">JavaScript</option>
<option data-lang="HTML mixed-mode">HTML</option>
<option data-lang="CSS">CSS</option>
</select>
</div>
<div class="new-inner">
<textarea class="demotext" style="display: none;"></textarea>
<div class="remove-widget"></div>
</div>
</div>
答案 0 :(得分:0)
我在模式上使用了错误的语法。
这里是解决方法: