[英]How to allow user to input a color (non hex or rbga) for list customization but make sure it's valid
只是想知道是否有人知道将其实现为代码的最佳方法。 是否有检查字符串是否为有效颜色的方法?
我想允许用户单击按钮来更改颜色,然后输入颜色名称,从而更改其列表的背景颜色。
您可以从规范CSS Color Module Level 4获得有效的颜色名称,将pattern
属性设置为RegExp
作为由|
分隔的数组中的字符串|
对于OR
; 在input type="text"
元素上设置required
属性,在相邻的<label>
元素处向用户提供通知,告知颜色名称是否有效。
window.onload = () => { const cssColor = "https://drafts.csswg.org/css-color/"; const input = document.querySelector("form input[type=text]"); const button = document.querySelector("form input[type=button]"); const img = document.querySelector("form img"); const span = document.querySelector("span"); fetch(cssColor) .then(response => response.text()) .then(html => { const parser = new DOMParser(); const doc = parser.parseFromString(html, "text/html"); const colorNames = Array.from( doc.querySelectorAll(".named-color-table dfn") , ({textContent}) => textContent ); console.log(colorNames); input.pattern = colorNames .concat(colorNames.map(color => color.toUpperCase())).join("|"); button.addEventListener("click", e => { if (input.checkValidity()) img.style.backgroundColor = input.value; }); input.removeAttribute("disabled"); button.removeAttribute("disabled"); span.style.display = "none"; }) }
form * { padding: 4px; margin: 4px; } img { border: 1px solid black; } #colorName:invalid+[for=colorName]:after { content: "Invalid color"; color: red; } #colorName:valid+[for=colorName]:after { content: "Valid color"; color: green; }
<span>loading valid color names..</span> <form> <input id="colorName" type="text" required pattern="" disabled/><label for="colorName"></label><br> <input type="button" value="click" disabled><br> <img alt="color" width="100px" height="100px"> </form>
只需将颜色分配给样式属性,然后检查属性的长度> 0就可以了
例如你可以这样做
function testColor(color) {
var head = document.head || document.getElementsByTagName('head')[0];
head.style.backgroundColor = ''; // clear it first - which makes it valid
head.style.backgroundColor = color;
return head.style.backgroundColor.length > 0;
}
在Firefox,Chrome,IE和Edge中进行了测试
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.