如何使用JavaScript将十六进制转换为RGBA值?
在设计网页时,我们使用颜色来使网页更具吸引力和参与性。我们通常使用十六进制代码来表示颜色,但有时我们需要为颜色添加透明度,这可以通过RGBA值来实现。
十六进制颜色值表示为#RRGGBBAA,RGBA颜色值表示为rgba(red, green, blue, alpha)。以下是一些RGBA和十六进制值的示例:
Input: #7F11E0 Output: rgba( 127, 17, 224, 1 ) Input: #1C14B0 Output: rgba( 28, 20, 176, 1 )
在本文中,我们将讨论使用Javascript将十六进制转换为RGBA的多种方法。
使用parseInt和String.substring方法
使用数组解构和正则表达式
使用ParseInt和String.substring方法
parseInt()函数接受两个参数:表示数字的字符串和表示基数的数字。然后,它将字符串转换为指定基数的整数并返回结果。
String.substring方法用于通过获取起始和结束位置来提取字符串的某些部分。
要将十六进制转换为RGBA,我们使用以下步骤。
去掉#号,并使用String.substring方法逐个提取十六进制字符串的每对两个字符。
提取后,使用parseInt方法将每对转换为整数。众所周知,这些对是十六进制代码,因此我们需要将parseInt的第二个参数传递为16。
将每对十六进制代码转换为整数后,将其连接到RGBA格式。
示例
在这个示例中,我们将十六进制代码转换为RGBA。
<!DOCTYPE html>
<html>
<head>
<title>Convert Hex to RGBA value using JavaScript</title>
</head>
<body>
<h3>Converting Hex to RGBA value parseInt() and String.substring() methods</h3>
<p id="input"> Hex Value: </p>
<p id="output"> RGBA Value: </p>
<script>
let hex = "#7F11E0";
let opacity = "1";
// Convert each hex character pair into an integer
let red = parseInt(hex.substring(1, 3), 16);
let green = parseInt(hex.substring(3, 5), 16);
let blue = parseInt(hex.substring(5, 7), 16);
// Concatenate these codes into proper RGBA format
let rgba = ` rgba(${red}, ${green}, ${blue}, ${opacity})`
// Get input and output fields
let inp = document.getElementById("input");
let opt = document.getElementById("output");
// Print the values
inp.innerHTML += hex;
opt.innerText += rgba;
</script>
</body>
</html>
使用Array.map()和String.match()方法
Javascript数组map()方法创建一个新数组,其中包含对该数组中每个元素调用提供的函数的结果。
String.match方法用于在将字符串与正则表达式匹配时检索匹配项。
要将十六进制转换为RGBA,我们使用以下步骤。
使用正则表达式/\w\w/g和String.match方法匹配十六进制字符串中每两个连续的字母数字字符的序列。
您将得到一个包含三对字母数字字符的数组,并使用Array.map和parseInt方法将这些字符转换为整数。
示例
在这个示例中,我们将十六进制代码转换为RGBA。
<!DOCTYPE html>
<html>
<head>
<title>Converting Hex to RGBA value using JavaScript</title>
</head>
<body>
<h3>Convert Hex to RGBA value using Array.map() and String.match() methods</h3>
<p id="input"> Hex: </p>
<p id="output"> RGBA: </p>
<script>
let hex = "#7F11E0";
let opacity = "1";
// Use a regular expression to extract the individual color values from the hex string
let values = hex.match(/\w\w/g);
// Convert the hex color values to decimal values using parseInt() and store them in r, g, and b
let [r, g, b] = values.map((k) => parseInt(k, 16))
// Create the rgba string using the decimal values and opacity
let rgba = ` rgba( ${r}, ${g}, ${b}, ${opacity} )`
// Get input and output fields
let inp = document.getElementById("input");
let opt = document.getElementById("output");
// Print the values
inp.innerHTML += hex;
opt.innerText += rgba;
</script>
</body>
</html>
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP