Created
December 18, 2021 04:22
-
-
Save motsu0/ce739d705f9d7d969c9c276a49a60b1d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#input-num{ | |
display: block; | |
height: 1.5rem; | |
margin: 20px auto; | |
} | |
.output{ | |
box-sizing: border-box; | |
width: 90%; | |
margin: 20px auto; | |
border: 2px solid #777; | |
} | |
.output-title{ | |
padding: 4px 8px; | |
border-bottom: 1px solid #777; | |
background-color: #eee; | |
text-align: center; | |
} | |
.output-body{ | |
padding: 4px 8px; | |
text-align: right; | |
} | |
@media screen and (min-width:769px) { | |
.output{ | |
width: 50%; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input type="number" min="1" value="99" placeholder="1" id="input-num"> | |
<div class="output"> | |
<div class="output-title">数字和</div> | |
<div class="output-body"> | |
<div id="digit-sum"></div> | |
</div> | |
</div> | |
<div class="output"> | |
<div class="output-title">数字根</div> | |
<div class="output-body"> | |
<div id="digit-root"></div> | |
</div> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const input_num = document.getElementById('input-num'); | |
const digit_sum = document.getElementById('digit-sum'); | |
const digit_root = document.getElementById('digit-root'); | |
input_num.addEventListener('input',calc); | |
calc(); | |
function calc(){ | |
const num = Number(input_num.value); | |
//例外処理 | |
if(isNaN(num)){ | |
inputError(); | |
return; | |
} | |
if(!Number.isInteger(num)){ | |
inputError(); | |
return; | |
} | |
if(num==0){ | |
inputError(); | |
return; | |
} | |
if(num>Number.MAX_SAFE_INTEGER){ | |
inputError('数値が大きすぎます。'); | |
return; | |
} | |
//数字和 | |
const array = String(num).split('').map(v=>Number(v)); | |
const sum = array.reduce((a,b)=>a+b); | |
digit_sum.textContent = sum; | |
//数字根 | |
let root = num%9; | |
if(root==0) root=9; | |
digit_root.textContent = root; | |
} | |
function inputError(s){ | |
const str = s||'入力値に誤りがあります。'; | |
digit_sum.textContent = str; | |
digit_root.textContent = str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment