如何切换选项卡以在代码镜像中单击按钮时显示或隐藏

How to toggle tabs to show or hide on button click in code mirror

我正在为一个站点制作一个 python 编辑器,我正在为此目的使用 Code Mirror javascript 库。我有一个名为 toggle invisibles 的按钮。如果用户按下按钮,将显示空格和行尾标记。我也想显示标签。由于代码镜像仅显示空格和行尾,因此我添加了一种手动方式来显示制表符。

在代码镜像中,选项卡有html <span class="cm-tab" cm-text=" "></span>。我已经为 css 中的 .cm-tab class 设置了背景图片,以便可以看到带有这些图片的选项卡。

因为我想切换 span 元素的可见性,最初我将其设置为 visibility: hidden。在 javascript 中,当用户单击 toggle invisibles 按钮时,我会将可见性设置为 visible

代码如下:

CSS:

.cm-tab{
    background: url("url");
    visibility: hidden;
}

Javascript:

var showi = true;
$(".textarea-editor").each(function(index){
    var editor  = CodeMirror.fromTextArea($(this)[0],{
        mode: {name: "python", version: 3, singleLineStringErrors: true, globalVars: true}, 
        lineNumbers: true, 
        lineWrapping: true,
        indentUnit: 4,
        showInvisibles: false,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
        autoCloseBrackets: true,
        maxInvisibles: 16,
        matchBrackets: true,
        indentWithTabs: true,
    });
    $("#toggleInvisible").click(function(){
        editor.setOption('showInvisibles', showi);
        var tab-visibility = showi?"visible:"hidden";
        var style = $('<style>.cm-tab {visibility:'+tab-visibility+'} 
        </style>');
        $(".cm-tab".append(style);
        showi=showi?false:true;
    });
    editor.on('change', function(e){ var txt = editor.getValue();});
});

问题是,当我单击该按钮时,选项卡与背景图像一起显示。但是当我单击 enter 转到下一行时,选项卡变得不可见。基于此 post

,我还在点击功能中将样式属性附加到新创建的选项卡

Add CSS rule via jQuery for future created elements

我创建了两个样式标签并提供了 .cm-tab class。这是我的代码:

<style>.cm-tab{background:url();}</style>
<style id="tab-style">.cm-tab{visibility: hidden;}</style>

然后在javascript中更改#tab-style的html。

$("#tab-style").html(".cm-tab{visibility:visible}");