有效的十六进制颜色表示代码包含字母(AF)和整数(0-9),长度为3或6;我们通过正则表达式检查十六进制代码的有效性。
示例1:
<!DOCTYPE html> <head> <meta charset="UTF-8"> </head> <body> <p id="UP" style="font-size: 19px; font-weight: bold;"></p> <button onclick="GFG_Fun()">检查</button> <p id="DOWN" style="font-size: 24px; font-weight: bold;"></p> <p id="demo"></p> <script> var el_up = document.getElementById("UP"); var el_down = document.getElementById("DOWN"); var el_demo = document.getElementById("demo"); var colorCode = '#zabbcc'; el_up.innerHTML = "指定的16进制颜色字符串:"+ colorCode; var RegExp = /^#[0-9A-F]{6}$/i; function GFG_Fun() { el_down.innerHTML = RegExp.test(colorCode)?"有效地16进制颜色":"无效地16进制颜色"; el_demo.innerHTML="<span style='background-color: "+colorCode+";'>测试文字!查看背景颜色是否改变,改变了即颜色值有效。</span>" } </script> </body> </html>
示例2:
<!DOCTYPE html> <head> <meta charset="UTF-8"> </head> <body> <p id="UP" style="font-size: 19px; font-weight: bold;"></p> <button onclick="GFG_Fun()">检查</button> <p id="DOWN" style="font-size: 24px; font-weight: bold;"></p> <p id="demo"></p> <script> var el_up = document.getElementById("UP"); var el_down = document.getElementById("DOWN"); var el_demo = document.getElementById("demo"); var colorCode = '#aabbcc'; el_up.innerHTML = "指定的16进制颜色字符串:"+ colorCode; var RegExp = /^#[0-9A-F]{6}$/i; function GFG_Fun() { el_down.innerHTML = RegExp.test(colorCode)?"有效地16进制颜色":"无效地16进制颜色"; el_demo.innerHTML="<span style='background-color: "+colorCode+";'>测试文字!查看背景颜色是否改变,改变了即颜色值有效。</span>" } </script> </body> </html>
网友评论文明上网理性发言 已有0人参与
发表评论: