javascript - validate css properties without selector using CSSLint module Javascript
问题描述
I have a textarea which is basically the CodeMirror. I want to allow the user to only type the CSS properties without selector and then validate it using CSSLint. I am not sure how I can achieve this with the help of CSSLint.
For example, I want the user to type:
font-size: 10px;
and then validate it using CSSlint without the selector. CSSLint gives error when I don't use any selector. If a user type: h1{font-size:10px;}
then it works fine but for direct property it does not. I want to know about a rule or a module that can help me in achieving the desired objective where the user can just type the CSS properties as follows:
font-size: 10px;
color: white;
and then I can easily validate whether the properties are correct or not.
解决方案
您可以将用户输入包装在选择器中,然后使用 CSSLint。
例如,以下代码从带有的元素中读取属性id="input"
并将它们记录到控制台。
const userInput = document.getElementById("input").value;
// Wrap the user input in a style rule so CSSLint can
// verify it.
const results = CSSLint.verify(
"* {\n" + userInput + "\n}");
for (const message of results.messages) {
// Note: Subtract 1 from the line number because
// we added an extra line before the user input.
console.log(message.type, message.message,
"line", message.line - 1,
"col", message.col);
}
根据您的用例,您可能需要添加一些额外的检查以确保用户输入中没有任何会影响处理的 CSSLint 注释。
您还可以添加规则以确保所有用户输入都包含在一个样式规则中,如预期:
CSSLint.addRule({
// rule information
id: "unique-selector",
name: "Check for unique selector",
desc: "User input should consist only of "
+ "properties without selector",
url: "",
browsers: "All",
// initialization
init: function(parser, reporter) {
"use strict";
var rule = this,
first = true;
parser.addListener("startrule", function(event) {
var selectors = event.selectors;
if (first) {
first = false;
} else {
reporter.report(
"Unexpected start of rule",
selectors[0].line,
selectors[0].col,
rule);
}
});
},
});
推荐阅读
- javascript - addProject 不是函数(续集)
- react-native - 在 ReactNative 的 Flatlist 中显示 2 个项目
- publish-subscribe - PubSub 在确认截止日期后未重新发送消息
- php - 在上传php之前重命名多个文件错误只上传单个文件
- reactjs - 单击日历外部时,React-Day-Picker DayPicker 组件未关闭
- r - 我可以在不实际下载内容的情况下检查网站的状态吗?
- elasticsearch - Elasticsearch 相当于 SelectMany
- sql - 选择符合条件的查询
- vb.net - 调整面板/表单大小时如何在面板中重新排列多个按钮?
- javascript - 如何在JS中打乱二维数组的行