水曜日, 10月 14, 2026

Let's start JavaScript 114 
任意の比率1/nを指定1/nに変更したときのサイズ

前回とは異なり、任意の比率(1/n)のサイズを指定の比率(1/n)に変更したときのサイズを表示するHTMLを作成しました。サイズはpxですがmmでも同じです。

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

input {
width: 100px;
padding: 5px;
margin: 5px;
}

#result {
margin-top: 20px;
font-size: 1.2em;
font-weight: bold;
}
</style>
</head>
<body>

<h3>1/n 比率変更サイズ計算 px版</h3>

<label>
元のサイズ:&emsp;&emsp;&ensp;
<input type="number" id="originalSize" value="1000">
px
</label>

<br>

<label>
元の比率:&emsp;&emsp;1 /
<input type="number" id="originalRatio" value="2" min="1">
</label>

<br>

<label>
変更後の比率:1 /
<input type="number" id="newRatio" value="4" min="1">
</label>

<div id="result"></div>

<script>
const originalSize = document.getElementById("originalSize");
const originalRatio = document.getElementById("originalRatio");
const newRatio = document.getElementById("newRatio");
const result = document.getElementById("result");

function calculate() {
const size = Number(originalSize.value);
const oldN = Number(originalRatio.value);
const newN = Number(newRatio.value);

if (!size || !oldN || !newN) {
result.textContent = "";
return;
}

// 1/oldN → 1/newN に変更したときのサイズ
const newSize = size * oldN / newN;

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

originalSize.addEventListener("input", calculate);
originalRatio.addEventListener("input", calculate);
newRatio.addEventListener("input", calculate);

calculate();
</script>

</body>
</html>

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

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