土曜日, 10月 03, 2026

Let's start JavaScript 113 
任意の比率の%を指定の%に変更したときのサイズ

ちょっと面倒くさい処理が必要で、任意の比率(%)のサイズを指定の比率(%)に変更したときのサイズを表示するHTMLを作成しました。サイズはmmですがpxでも同じです。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>縮尺変換計算</title>
<style>
body {
font-family: sans-serif;
max-width: 300px;
background: black;
color: white;
margin: 10px auto;
padding: 20px;
}

label {
display: block;
margin-top: 15px;
}

input {
width: 100%;
box-sizing: border-box;
padding: 8px;
font-size: 16px;
}

#result {
margin-top: 25px;
padding: 15px;
background: #f0f0f0;
font-size: 20px;
font-weight: bold;
color: black;
}
</style>
</head>
<body>

<h2>比率変換</h2>

<label>
現在の比率(%)
<input type="number" id="currentRate" value="30" step="0.01">
</label>

<label>
変更後の比率(%)
<input type="number" id="targetRate" value="50" step="0.01">
</label>

<label>
現在のサイズ
<input type="number" id="currentSize" value="100" step="0.01">
</label>

<div id="result">
変更後のサイズ:166.67
</div>

<script>
function calculate() {
const currentRate =
        parseFloat(document.getElementById("currentRate").value);
const targetRate =
        parseFloat(document.getElementById("targetRate").value);
const currentSize =
        parseFloat(document.getElementById("currentSize").value);

if (
isNaN(currentRate) ||
isNaN(targetRate) ||
isNaN(currentSize) ||
currentRate === 0
) {
document.getElementById("result").textContent =
"正しい数値を入力してください";
return;
}

// 現在の比率 → 変更後の比率
const newSize = currentSize * (targetRate / currentRate);

document.getElementById("result").textContent =
`変更後のサイズ:${newSize.toFixed(2)}`;
}

document.querySelectorAll("input").forEach(input => {
input.addEventListener("input", calculate);
});

calculate();
</script>

</body>
</html>

実行直後のデフォルト画面です。

値を変更スレがライブで変更後のサイズが表示されます。