代码镜像 - 使给定行完全变灰

Code Mirror - Make a given line completely greyed out

我正在使用 Code Mirror,我正在尝试使给定的行完全变灰(因此它看起来像代码编辑器中通常看起来的注释)。到目前为止,我已经想出了这个:

editorDiv = this;

var editor = CodeMirror(function(elt) {
  editorDiv.parentNode.replaceChild(elt, editorDiv);
}, {
  value:       "function myScript(){\n\treturn 100; \n}\n",
  lineNumbers: true,
  readOnly:    "nocursor",
  theme:       "monokai"
});

console.log(editor);

var line = editor.getLineHandle(1);
console.log(line);

editor.addLineClass(line, "text", "greyed-out");

假设我希望 return 100; 行变灰(这是编辑器中的第 2 行和 API 中的第 1 行)。我的想法是将 greyed-out class 添加到此行并让 class 类似于:

.greyed-out { color: grey; }

但是,这不起作用,因为来自 Code Mirror 的其他 classes 具有更高的优先级并覆盖 greyed-out class。

我不确定是否有通过 Code Mirror 的 API 执行此操作的特定方法,或从更高优先级 classes 中删除不需要的属性的一般方法。

有人可以帮我解决这个问题吗?

在这种情况下,您可以使用 !important:

.greyed-out { color: grey !important; }

然而,应该避免它,只有在必要时才使用它。您还可以通过扩展选择器来增加样式的特异性。

从另一个 class 中 over-ride 规则的最佳方法是为您的选择器提供更高的特异性,例如:

#container .foo-list li .greyed-out { color: grey; }

或者,您可以在规则中使用 !important,但这被认为是不好的做法,应尽可能避免。

.greyed-out { color: grey !important; }