calculator.zip
0.00MB

 

js로 만든 계산기

 

html

<!DOCTYPE html>
<html>
<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>Calculator</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='./style.css'>
</head>
<body>
    <div class="container">
        <div class="result">
            <p id="result">0</p>
        </div>
        <div class="buttons">
            <button></button>
            <button>%</button>
            <button>C</button>
            <button>D</button>
            <button>7</button>
            <button>8</button>
            <button>9</button>
            <button>/</button>
            <button>4</button>
            <button>5</button>
            <button>6</button>
            <button>*</button>
            <button>1</button>
            <button>2</button>
            <button>3</button>
            <button>+</button>
            <button>.</button>
            <button>0</button>
            <button class="equal">=</button>
            <button>-</button>
        </div>
    </div>
    <script src='./app.js'></script>
</body>
</html>

 

js

let buttons = document.querySelectorAll('button');

buttons.forEach(button => {
   button.addEventListener('click', getInputValue);
});

function getInputValue(e){
    let input = e.target.innerText
    printValue(input);
}

function printValue(val){
  let out = document.querySelector("#result");
  let current = out.innerHTML;
  if(out.innerHTML == "0"){
    if(val != "C" && val != "D"){ 
      out.innerHTML = "";
      out.innerHTML += val;
    }
  }
  else{
    if(val == "D" ){
      out.innerText = current.slice(0,-1);
      if(out.innerHTML.length <= 1){
        out.innerHTML = "0";
      }
    }
    if(val != "C" && val !="D" && val != "="){ 
      out.innerHTML += val;
    }
    if(val == "="){
      let res = out.innerHTML;
      out.innerHTML = eval(res);
    }
    if(val == "C"){
      out.innerHTML = "0";
    }
  }
}

 

css

@import url("https://fonts.googleapis.com/css2?family=Poppins:ital,wght@200,400&display=swap");

* {
	box-sizing: border-box;
}

body {
	font-family: "Poppins", sans-serif;
	margin: 0;
}

.container{
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);
    background-color: #fafafa;
    box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.3);
    border-radius: 8px;
}

.result{
	text-align: right;
	background-color: #212121;
	color: #fafafa;
	border-radius: 8px 8px 0 0;
	padding: 20px;
	font-size: 2.5rem;
}

.buttons{
    display: grid;
    grid-template-columns: auto auto auto auto;
}

.buttons button{
    width: 80px;
    height: 80px;
    border: none;
    font-size: 1.5rem;
    text-align: center;
    transition: .2s linear all;
}

.buttons button:hover{
    background-color: #e0e0e0;
    
}

.buttons button:active{
    background-color: #bdbdbd;
}

.equal{
    background-color: #f57f17;
}