有一个输入字段,其值已更改。该值通过 JavaScript 函数更改。这始终是十进制数。
十进制数的最后 2 位应具有不同的字体大小:10 px
function generate(){
var generatedValue=Math.floor(Math.random() * 100000)/100.0;
document.getElementById("myinput").value = generatedValue;
};
body{
margin: 20px;
font-size: 30px;
}
.inputClass {
font-size: 20px;
max-width: 200px;
margin: 20px 0 20px 0;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<h1>Hello World</h1>
<button onclick="generate()">Generate</button>
<div class="input-group" class="numberDiv">
<input id="myinput" class="form-control inputClass" value="0.00" disabled>
</div>
</body>
</html>
最佳答案
您不能在输入元素内使用多个字体大小,因此您需要使用以相同方式设置样式的不同元素(例如 output
元素)
在下面的示例中,我将输入元素保留为隐藏
元素,以防您需要它在表单中传递数据
function generate(){
var generatedValue = Math.floor(Math.random() * 100000)/100.0;
var result = generatedValue.toFixed(2);
var amount = result.split('.');
document.getElementById("myinput").value = result;
document.querySelector('output').innerHTML = amount[0] + '.<small>' + amount[1] + '</small>';
};
body{
margin: 20px;
font-size: 30px;
}
.inputClass, output {
font-size: 20px;
max-width: 200px;
margin: 20px 0 20px 0;
}
/* Declarations taken from the style applied to .inputClass */
div output {
display: block;
border-radius: 3px;
background: #e9ecef;
flex: 1 1 auto;
padding: .375rem .75rem;
font-size: 1rem;
border: 1px solid #ced4da;
height: calc(1.5em + .75rem + 2px);
color: #495057;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
<h1>Hello World</h1>
<button onclick="generate()">Generate</button>
<div class="input-group" class="numberDiv">
<input id="myinput" class="form-control inputClass" value="0.00" disabled type="hidden" />
<output>0.<small>00</small></output>
</div>
</body>
</html>
关于javascript - 如何更改 HTML 网站输入字段中最后 2 个字符的字体大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66563376/