Javascript 如何允许用户为列表自定义输入颜色(非十六进制或rbga),但确保其有效
只是想知道是否有人知道将其实现为代码的最佳方法。有没有检查字符串是否为有效颜色的方法Javascript 如何允许用户为列表自定义输入颜色(非十六进制或rbga),但确保其有效,javascript,Javascript,只是想知道是否有人知道将其实现为代码的最佳方法。有没有检查字符串是否为有效颜色的方法 我希望允许用户单击按钮更改颜色,然后输入颜色名称,更改其列表的背景颜色。只需将颜色指定给样式属性,并检查属性的长度是否大于0,即可完成此任务 e、 你可以这样做 function testColor(color) { var head = document.head || document.getElementsByTagName('head')[0]; head.style.backgroun
我希望允许用户单击按钮更改颜色,然后输入颜色名称,更改其列表的背景颜色。只需将颜色指定给样式属性,并检查属性的长度是否大于0,即可完成此任务 e、 你可以这样做
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中进行测试您可以从规范中获取有效的颜色名称,将pattern属性设置为RegExp作为字符串,从以| for或分隔的数组中获取;在输入类型=文本元素处设置必需属性,在相邻元素处向用户提供颜色名称是否有效的通知 window.onload==>{ 常数cssColor=https://drafts.csswg.org/css-color/; 常量输入=document.querySelectorform输入[类型=文本]; const button=document.queryselector表单输入[type=button]; const img=document.querySelectorform img; const span=document.querySelectorspan; 取色 .thenresponse=>response.text .thenhtml=>{ const parser=新的DOMParser; const doc=parser.parseFromStringhtml,text/html; const colorNames=Array.from doc.queryselectoral.named-color-table dfn ,{textContent}=>textContent ; console.logcolorNames; input.pattern=颜色名称 .concatcolorNames.mapcolor=>color.toUpperCase.join |; button.AddEventListener单击,e=>{ if input.checkValidity img.style.backgroundColor=input.value; }; input.RemoveAttributed已禁用; button.RemoveAttribute已禁用; span.style.display=无; } } 表格*{ 填充:4px; 保证金:4倍; } img{ 边框:1px纯黑; } colorName:无效+[for=colorName]:之后{ 内容:无效颜色; 颜色:红色; } colorName:valid+[for=colorName]:在{ 内容:有效颜色; 颜色:绿色; } 正在加载有效的颜色名称。。
你想检查一个单词是否是有效的颜色名称吗?正确!我希望用户能够输入他们想要的颜色,但要确保它不仅仅是一些随机词。@firefox上的JaromandaX在单击Inspect Element Q后单击网络选项卡上的原始标题。不确定firebug为什么不显示所有响应标题。