paint-brush
A melhor maneira de criar uma calculadora simples usando HTML e JavaScriptby@shuseel
2,220
2,220

A melhor maneira de criar uma calculadora simples usando HTML e JavaScript

Shuseel Baral5m2023/08/01
Read on Terminal Reader

Aqui estão as etapas para fazer uma calculadora simples usando HTML e JavaScript que pode executar aritmética simples em inteiros inteiros.
featured image - A melhor maneira de criar uma calculadora simples usando HTML e JavaScript
Shuseel Baral HackerNoon profile picture
0-item

Construir uma calculadora simples usando HTML e JavaScript pode ser um trabalho divertido e educacional para desenvolvedores da Web que estão apenas começando.


Ao combinar os recursos de HTML para design de interface do usuário e JavaScript para manipulação de cálculo, você pode construir uma calculadora interativa e funcional diretamente em seu navegador.


Nesta postagem, vamos guiá-lo pelo processo passo a passo de criação de uma calculadora básica a partir do zero, enquanto também exploramos os princípios da programação da web ao longo do caminho.


Para começar, devemos primeiro criar o ambiente do projeto. Construiremos a estrutura HTML básica que servirá como base para nossa calculadora. Além disso, para tornar a calculadora visualmente mais atraente, configuraremos sua aparência usando CSS.


Por fim, configuraremos o ambiente JavaScript para adicionar funcionalidade à nossa calculadora.


Índice

  • Etapas para criar uma calculadora simples usando HTML e JavaScript
      1. Projetando a interface do usuário
      1. Manipulando a entrada do usuário
      1. Realizando o Cálculo
  • Código HTML completo para uma calculadora HTML simples
  • Visualização da calculadora HTML simples
  • Conclusão

Etapas para criar uma calculadora simples usando HTML e JavaScript

Aqui estão as etapas para fazer uma calculadora simples usando HTML e JavaScript que pode executar aritmética simples em inteiros inteiros.


Entradas de texto e botão são usadas em uma tabela dentro de um elemento de formulário, e o evento OnClick foi usado para colocar valores de botão na tela ou para avaliar os números.

1. Projetando a interface do usuário

A interface do usuário (UI) é a face frontal da calculadora. Criaremos uma exibição limpa para exibição de entrada e resultados. Também forneceremos botões interativos para números inteiros e operadores. Nosso objetivo é produzir um design intuitivo e fácil de usar que enriqueça todos os aspectos dos usuários de calculadoras.


Use as etapas a seguir para projetar a interface do usuário da calculadora.


Etapa 1. Inicialmente, crie a tag <html> junto com o elemento <form> e a tag <body> conforme abaixo.

 <html> <head><title>A Simple Calculator Using HTML</title></head> <body> <h3>A Simple Calculator Using HTML</h3> <form Name="calc"> </form> </body> </html>


Etapa 2. Agora, crie uma tabela dentro da tag <form>……</form> usando a tag <table> …..</table> e insira dois tipos de texto de entrada e botões nos dados da tabela da linha da tabela usando <tr <td>….</td></tr> marca.

 <table id="calc" border=2> <tr> <td colspan=5><input id="btn" name="display" type="text"></td> <td style="display:none"><input name="M" type="number"></td> </tr> </table>


Etapa 3. Em seguida, crie botões usando a tag <input> e também defina o “id” e o “valor” desses botões na linha da tabela com as tags <tr><td>….</td></tr> como apresentado abaixo.

 <tr> <td><input id="btn" type=button value="MC"></td> <td><input id="btn" type=button value="0"></td> <td><input id="btn" type=button value="1"></td> <td><input id="btn" type=button value="2"></td> <td><input id="btn" type=button value="+"></td> </tr> <tr> <td><input id="btn" type=button value="MS"></td> <td><input id="btn" type=button value="3"></td> <td><input id="btn" type=button value="4"></td> <td><input id="btn" type=button value="5"></td> <td><input id="btn" type=button value="-"></td> </tr> <tr> <td><input id="btn" type=button value="MR"></td> <td><input id="btn" type=button value="6"></td> <td><input id="btn" type=button value="7"></td> <td><input id="btn" type=button value="8"></td> <td><input id="btn" type=button value="x"></td> </tr> <tr> <td><input id="btn" type=button value="M+"></td> <td><input id="btn" type=button value="9"></td> <td><input id="btn" type=button value="±"></td> <td><input id="btn" type=button value="="></td> <td><input id="btn" type=button value="/"></td> </tr> <tr> <td><input id="btn" type=button value="1/x"></td> <td><input id="btn" type=button value="."></td> <td><input id="btn" type=button value="x2"></td> <td><input id="btn" type=button value="√"></td> <td><input id="btn" type=button value="C"></td> </tr>


Etapa 4. Por fim, adicione o seguinte código CSS para fornecer o design da calculadora com a tag <style>…..</style> conforme fornecido abaixo.

 <style> #calc{width:300px;height:250px;} #btn{width:100%;height:40px;font-size:20px;} </style>

2. Manipulando a entrada do usuário

Use as etapas a seguir para projetar a interface do usuário da calculadora.


#Passo 1. Atribua um evento “onkeypress” para um botão de exibição que foi criado para exibir a entrada e o resultado do cálculo conforme indicado abaixo.

 <tr> <td colspan=5><input id="btn" name="display" onkeypress="return event.charCode >= 48 && event.charCode <= 57" type="text"></td> <td style="display:none"><input name="M" type="number"></td> </tr>


Etapa 2. Atribua um evento OnClick para todos os botões com números e operadores aritméticos conforme abaixo.

 <tr> <td><input id="btn" type=button value="MC" OnClick="calc.M.value=''"></td> <td><input id="btn" type=button value="0" OnClick="calc.display.value+='0'"></td> <td><input id="btn" type=button value="1" OnClick="calc.display.value+='1'"></td> <td><input id="btn" type=button value="2" OnClick="calc.display.value+='2'"></td> <td><input id="btn" type=button value="+" OnClick="calc.display.value+='+'"></td> </tr> <tr> <td><input id="btn" type=button value="MS" OnClick="calc.M.value=calc.display.value"></td> <td><input id="btn" type=button value="3" OnClick="calc.display.value+='3'"></td> <td><input id="btn" type=button value="4" OnClick="calc.display.value+='4'"></td> <td><input id="btn" type=button value="5" OnClick="calc.display.value+='5'"></td> <td><input id="btn" type=button value="-" OnClick="calc.display.value+='-'"></td> </tr> <tr> <td><input id="btn" type=button value="MR" OnClick="calc.display.value=calc.M.value"></td> <td><input id="btn" type=button value="6" OnClick="calc.display.value+='6'"></td> <td><input id="btn" type=button value="7" OnClick="calc.display.value+='7'"></td> <td><input id="btn" type=button value="8" OnClick="calc.display.value+='8'"></td> <td><input id="btn" type=button value="x" OnClick="calc.display.value+='*'"></td> </tr>

3. Realizando o Cálculo

Atribua um evento OnClick para todos os operadores aritméticos, coloque aspas duplas com espaço (“”) para o botão Clear(C) e use a função eval() para avaliar os números no evento OnClick conforme indicado abaixo.

 <tr> <td><input id="btn" type=button value="M+" OnClick="calc.M.value=(Number(calc.M.value))+(Number(calc.display.value))"></td> <td><input id="btn" type=button value="9" OnClick="calc.display.value+='9'"></td> <td><input id="btn" type=button value="±" OnClick="calc.display.value=(calc.display.value==Math.abs(calc.display.value)?-(calc.display.value):Math.abs(calc.display.value))"> </td> <td><input id="btn" type=button value="=" OnClick="calc.display.value=eval(calc.display.value)"></td> <td><input id="btn" type=button value="/" OnClick="calc.display.value+='/'"></td> </tr> <tr> <td><input id="btn" type=button value="1/x" OnClick="calc.display.value=1/calc.display.value"></td> <td><input id="btn" type=button value="." OnClick="calc.display.value+='.'"></td> <td><input id="btn" type=button value="x2" OnClick="calc.display.value=Math.pow(calc.display.value,2)"></td> <td><input id="btn" type=button value="√" OnClick="calc.display.value=Math.sqrt(calc.display.value)"></td> <td><input id="btn" type=button value="C" OnClick="calc.display.value=''"></td> </tr>

Código HTML completo para uma calculadora HTML simples

 <html> <head></head> <body> <h3>Simple Calculator</h3> <br/> <style> #calc{width:300px;height:250px;} #btn{width:100%;height:40px;font-size:20px;} </style> <form Name="calc"> <table id="calc" border=2> <tr> <td colspan=5><input id="btn" name="display" onkeypress="return event.charCode >= 48 && event.charCode <= 57" type="text"></td> <td style="display:none"><input name="M" type="number"></td> </tr> <tr> <td><input id="btn" type=button value="MC" OnClick="calc.M.value=''"></td> <td><input id="btn" type=button value="0" OnClick="calc.display.value+='0'"></td> <td><input id="btn" type=button value="1" OnClick="calc.display.value+='1'"></td> <td><input id="btn" type=button value="2" OnClick="calc.display.value+='2'"></td> <td><input id="btn" type=button value="+" OnClick="calc.display.value+='+'"></td> </tr> <tr> <td><input id="btn" type=button value="MS" OnClick="calc.M.value=calc.display.value"></td> <td><input id="btn" type=button value="3" OnClick="calc.display.value+='3'"></td> <td><input id="btn" type=button value="4" OnClick="calc.display.value+='4'"></td> <td><input id="btn" type=button value="5" OnClick="calc.display.value+='5'"></td> <td><input id="btn" type=button value="-" OnClick="calc.display.value+='-'"></td> </tr> <tr> <td><input id="btn" type=button value="MR" OnClick="calc.display.value=calc.M.value"></td> <td><input id="btn" type=button value="6" OnClick="calc.display.value+='6'"></td> <td><input id="btn" type=button value="7" OnClick="calc.display.value+='7'"></td> <td><input id="btn" type=button value="8" OnClick="calc.display.value+='8'"></td> <td><input id="btn" type=button value="x" OnClick="calc.display.value+='*'"></td> </tr> <tr> <td><input id="btn" type=button value="M+" OnClick="calc.M.value=(Number(calc.M.value))+(Number(calc.display.value))"></td> <td><input id="btn" type=button value="9" OnClick="calc.display.value+='9'"></td> <td><input id="btn" type=button value="±" OnClick="calc.display.value=(calc.display.value==Math.abs(calc.display.value)?-(calc.display.value):Math.abs(calc.display.value))"> </td> <td><input id="btn" type=button value="=" OnClick="calc.display.value=eval(calc.display.value)"></td> <td><input id="btn" type=button value="/" OnClick="calc.display.value+='/'"></td> </tr> <tr> <td><input id="btn" type=button value="1/x" OnClick="calc.display.value=1/calc.display.value"></td> <td><input id="btn" type=button value="." OnClick="calc.display.value+='.'"></td> <td><input id="btn" type=button value="x2" OnClick="calc.display.value=Math.pow(calc.display.value,2)"></td> <td><input id="btn" type=button value="√" OnClick="calc.display.value=Math.sqrt(calc.display.value)"></td> <td><input id="btn" type=button value="C" OnClick="calc.display.value=''"></td> </tr> </table> </form> </body> </html>

Visualização da Calculadora HTML Simples

Você pode ver e usar a calculadora HTML do artigo original publicado no InfoTechSite.


Clique aqui para ver a calculadora HTML.


Também publicado aqui