JavaScript 如何将像素值转换为数字值
在本文中,我们将看到如何通过JavaScript将包含像素值的字符串值转换为整数值。
有两种方法可以将像素值转换为数字值,它们是:
- 使用parseInt()方法
- 使用RegExp
方法1:使用parseInt()方法
这个方法以字符串作为第一个参数并返回整数值。
示例: 这个示例实现了上述方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
How to convert a pixel value to a
number value using JavaScript ?
</title>
</head>
<body>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<p id="checkFontSize" style="font-size: 19px">
Click on Button to get this
font size value in number
</p>
<button onclick="GFG_Fun()">
Click Here
</button>
<p id="result"></p>
<script>
const str = document.getElementById("checkFontSize");
const res = document.getElementById("result");
const fontSizePX = str.style.fontSize;
function GFG_Fun() {
res.innerHTML = "Integer value is " +
parseInt(fontSizePX, 10);
}
</script>
</body>
</html>
输出:

方法2: 使用RegExp
RegExp元素 用于将 ‘px’ 替换为空字符串,并使用 Number() 方法将结果转换为整数。
示例: 这个示例实现了上述方法。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
How to convert a pixel value to a
number value using JavaScript ?
</title>
</head>
<body>
<h1 style="color:green;">
GeeksforGeeks
</h1>
<p id="checkFontSize" style="font-size: 19px">
Click on Button to get this
font size value in number
</p>
<button onclick="GFG_Fun()">
Click Here
</button>
<p id="result"></p>
<script>
const str = document.getElementById("checkFontSize");
const res = document.getElementById("result");
const fontSizePX = str.style.fontSize;
function GFG_Fun() {
res.innerHTML = "Integer value is " +
Number(fontSizePX.replace(/px$/, ''));
}
</script>
</body>
</html>
输出:

极客教程