hxt1218 2 months ago
parent 9ef3cfd81f
commit 0172a7782a

@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>进制转换</title>
<title>进制转换</title>
<style>
body {
font-family: Arial, sans-serif;
@ -17,15 +17,23 @@
display: block;
margin-bottom: 10px;
}
#result {
font-weight: bold;
color: #333;
}
.error {
color: red;
}
</style>
</head>
<body>
<h2>任意进制转换器</h2>
<label for="fromBase">输入进制 (2-16):</label>
<input type="number" id="fromBase" min="2" max="16" required>
<label for="number">输入数字:</label>
<input type="text" id="number" required>
<input type="text" id="number" placeholder="例如1010" required>
<label for="toBase">转换为进制 (2-16):</label>
<input type="number" id="toBase" min="2" max="16" required>
@ -36,20 +44,43 @@
<div id="result"></div>
<script>
document.getElementById('convertButton').addEventListener('click', function() {
document.getElementById('convertButton').addEventListener('click', handleConversion);
function handleConversion() {
const fromBase = parseInt(document.getElementById('fromBase').value);
const number = document.getElementById('number').value;
const number = document.getElementById('number').value.trim();
const toBase = parseInt(document.getElementById('toBase').value);
const resultElement = document.getElementById('result');
// 先将输入的任意进制数转换为十进制
const decimalValue = parseInt(number, fromBase);
// 清除之前的结果和错误信息
resultElement.textContent = '';
// 验证输入的数字是否合法
const validationMessage = validateInput(number, fromBase);
if (validationMessage) {
resultElement.textContent = validationMessage;
resultElement.className = 'error';
return;
}
// 将十进制数转换为目标进制
// 转换为十进制并转换为目标进制
const decimalValue = parseInt(number, fromBase);
const convertedValue = decimalValue.toString(toBase).toUpperCase();
// 显示结果
document.getElementById('result').textContent = convertedValue;
});
resultElement.textContent = convertedValue;
resultElement.className = ''; // 清除错误样式
}
function validateInput(numStr, base) {
const validChars = '0123456789ABCDEF'.slice(0, base);
const isValid = [...numStr].every(char => validChars.includes(char.toUpperCase()));
if (!isValid) {
return `输入的数字不符合${base}进制规则!`;
}
return null;
}
</script>
</body>
</html>

Loading…
Cancel
Save