forks

Creation chat

ClarkZhang
create a caculator
02-25 13:37

登录 后可以评论

Assistant
(HTML code has been generated and updated; see above for the current version.) This calculator features: 1. **Modern UI Design**: - Clean, rounded buttons with appropriate spacing - Responsive layout that works on mobile and desktop - Dark/light mode support with theme toggle - Visual feedback on button presses 2. **Full Functionality**: - Basic operations (addition, subtraction, multiplication, division) - Percentage calculations - Decimal point support - Clear (C) and backspace (⌫) functions - Error handling (e.g., division by zero) 3. **Enhanced User Experience**: - Keyboard support for all operations - Visual distinction between number, operator, and function buttons - Display showing current and previous operations - Responsive button animations - Error modals for invalid operations 4. **Technical Features**: - Uses Tailwind CSS for styling - localStorage for theme preference persistence - Semantic HTML structure - Proper error handling with custom modals - Touch-friendly interface with appropriate sizing The calculator works by maintaining state for current/previous operands and the selected operation. When you press equals or another operator, it computes the result and updates the display. You can use either mouse/touch or keyboard to interact with it. Note: There's a Console panel in the bottom-right of the preview where you can see logs if needed for debugging.
▼ Code
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Simple Calculator</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script>tailwind.config = { darkMode: 'class' }</script>
    <style>
        .calculator-button {
            @apply flex items-center justify-center rounded-full h-16 w-16 text-xl font-medium transition-all duration-100 active:scale-95 focus:outline-none;
        }
        .number-button {
            @apply bg-gray-100 hover:bg-gray-200 dark:bg-gray-700 dark:hover:bg-gray-600 text-gray-800 dark:text-gray-200;
        }
        .operator-button {
            @apply bg-blue-500 hover:bg-blue-600 dark:bg-blue-600 dark:hover:bg-blue-700 text-white;
        }
        .function-button {
            @apply bg-gray-200 hover:bg-gray-300 dark:bg-gray-600 dark:hover:bg-gray-500 text-gray-700 dark:text-gray-200;
        }
        .equals-button {
            @apply bg-green-500 hover:bg-green-600 dark:bg-green-600 dark:hover:bg-green-700 text-white;
        }
        .zero-button {
            @apply w-full rounded-xl px-4;
        }
    </style>
</head>
<body class="min-h-screen bg-slate-50 dark:bg-slate-900 text-slate-900 dark:text-slate-100 flex flex-col items-center justify-center p-4">
    <!-- Theme toggle -->
    <button id="theme-toggle-btn" class="fixed top-4 right-4 z-10 p-2 rounded-md hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 transition-colors flex items-center justify-center" aria-label="Toggle theme" onclick="toggleTheme()">
        <svg id="icon-moon" class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path d="M21.752 15.002A9.72 9.72 0 0 1 18 15.75c-5.385 0-9.75-4.365-9.75-9.75 0-1.33.266-2.597.748-3.752A9.753 9.753 0 0 0 3 11.25C3 16.635 7.365 21 12.75 21a9.753 9.753 0 0 0 9.002-5.998z"/></svg>
        <svg id="icon-sun" class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24" aria-hidden="true" style="display:none"><circle cx="12" cy="12" r="4"></circle><path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41"></path></svg>
    </button>
    <script>
        function toggleTheme(){ var el=document.documentElement; var isDark=!el.classList.contains('dark'); el.classList.toggle('dark',isDark); localStorage.setItem('theme',isDark?'dark':'light'); applyTheme(isDark); }
        function applyTheme(isDark){ document.getElementById('icon-moon').style.display=isDark?'none':'block'; document.getElementById('icon-sun').style.display=isDark?'block':'none'; }
        document.addEventListener('DOMContentLoaded',function(){ var saved=localStorage.getItem('theme'); var isDark=saved==='dark'||(!saved&&window.matchMedia('(prefers-color-scheme: dark)').matches); document.documentElement.classList.toggle('dark',isDark); applyTheme(isDark); });
    </script>

    <div class="w-full max-w-md">
        <h1 class="text-3xl font-bold text-center mb-6">Simple Calculator</h1>
        
        <div class="bg-white dark:bg-slate-800 rounded-2xl shadow-xl overflow-hidden border border-slate-200 dark:border-slate-700">
            <!-- Display -->
            <div class="p-4 bg-slate-100 dark:bg-slate-700">
                <div id="previous-operand" class="text-right text-slate-500 dark:text-slate-400 text-lg h-6 overflow-x-auto whitespace-nowrap"></div>
                <div id="current-operand" class="text-right text-slate-900 dark:text-slate-100 text-3xl font-bold h-12 overflow-x-auto whitespace-nowrap">0</div>
            </div>
            
            <!-- Keypad -->
            <div class="p-4">
                <div class="grid grid-cols-4 gap-3">
                    <button class="calculator-button function-button" onclick="clearAll()">C</button>
                    <button class="calculator-button function-button" onclick="deleteLast()">⌫</button>
                    <button class="calculator-button function-button" onclick="chooseOperation('%')">%</button>
                    <button class="calculator-button operator-button" onclick="chooseOperation('÷')">÷</button>
                    
                    <button class="calculator-button number-button" onclick="appendNumber('7')">7</button>
                    <button class="calculator-button number-button" onclick="appendNumber('8')">8</button>
                    <button class="calculator-button number-button" onclick="appendNumber('9')">9</button>
                    <button class="calculator-button operator-button" onclick="chooseOperation('×')">×</button>
                    
                    <button class="calculator-button number-button" onclick="appendNumber('4')">4</button>
                    <button class="calculator-button number-button" onclick="appendNumber('5')">5</button>
                    <button class="calculator-button number-button" onclick="appendNumber('6')">6</button>
                    <button class="calculator-button operator-button" onclick="chooseOperation('-')">-</button>
                    
                    <button class="calculator-button number-button" onclick="appendNumber('1')">1</button>
                    <button class="calculator-button number-button" onclick="appendNumber('2')">2</button>
                    <button class="calculator-button number-button" onclick="appendNumber('3')">3</button>
                    <button class="calculator-button operator-button" onclick="chooseOperation('+')">+</button>
                    
                    <button class="calculator-button number-button zero-button col-span-2" onclick="appendNumber('0')">0</button>
                    <button class="calculator-button number-button" onclick="appendNumber('.')">.</button>
                    <button class="calculator-button equals-button" onclick="compute()">=</button>
                </div>
            </div>
        </div>
        
        <div class="mt-8 text-center text-slate-600 dark:text-slate-400">
            <p>Perform basic calculations with this simple calculator</p>
        </div>
    </div>

    <script>
        // Calculator state
        let currentOperand = '0';
        let previousOperand = '';
        let operation = undefined;
        let resetScreen = false;

        // DOM elements
        const currentOperandElement = document.getElementById('current-operand');
        const previousOperandElement = document.getElementById('previous-operand');

        // Update display
        function updateDisplay() {
            currentOperandElement.innerText = currentOperand;
            if (operation != null) {
                previousOperandElement.innerText = `${previousOperand} ${operation}`;
            } else {
                previousOperandElement.innerText = previousOperand;
            }
        }

        // Append number
        function appendNumber(number) {
            if (currentOperand === '0' || resetScreen) {
                currentOperand = number;
                resetScreen = false;
            } else {
                // Prevent multiple decimal points
                if (number === '.' && currentOperand.includes('.')) return;
                currentOperand += number;
            }
            updateDisplay();
        }

        // Choose operation
        function chooseOperation(op) {
            if (currentOperand === '') return;
            if (previousOperand !== '') {
                compute();
            }
            operation = op;
            previousOperand = currentOperand;
            resetScreen = true;
            updateDisplay();
        }

        // Compute calculation
        function compute() {
            let computation;
            const prev = parseFloat(previousOperand);
            const current = parseFloat(currentOperand);
            if (isNaN(prev) || isNaN(current)) return;
            
            switch (operation) {
                case '+':
                    computation = prev + current;
            break;
          case '×':
            computation = prev * current;
            break;
          case '÷':
            if (current === 0) {
                showModal('Cannot divide by zero!');
                return;
            }
            computation = prev / current;
            break;
          case '%':
            computation = prev % current;
            break;
          default:
            return;
        }
        currentOperand = computation.toString();
        operation = undefined;
        previousOperand = '';
        resetScreen = true;
        updateDisplay();
    }

    // Clear all
    function clearAll() {
        currentOperand = '0';
        previousOperand = '';
        operation = undefined;
        updateDisplay();
    }

    // Delete last character
    function deleteLast() {
        if (currentOperand.length === 1) {
            currentOperand = '0';
        } else {
            currentOperand = currentOperand.slice(0, -1);
        }
        updateDisplay();
    }

    // Initialize display
    updateDisplay();

    // Keyboard support
    document.addEventListener('keydown', event => {
        if (/[0-9]/.test(event.key)) {
            appendNumber(event.key);
        } else if (event.key === '.') {
            appendNumber('.');
        } else if (event.key === '+' || event.key === '-') {
            chooseOperation(event.key);
        } else if (event.key === '*') {
            chooseOperation('×');
        } else if (event.key === '/') {
            event.preventDefault();
            chooseOperation('÷');
        } else if (event.key === '%') {
            chooseOperation('%');
        } else if (event.key === 'Enter' || event.key === '=') {
            compute();
        } else if (event.key === 'Backspace') {
            deleteLast();
        } else if (event.key === 'Escape') {
            clearAll();
        }
    });
</script>

<!-- Custom modal -->
<div id="custom-modal" class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 hidden" aria-hidden="true">
  <div class="rounded-xl bg-white dark:bg-slate-800 p-6 shadow-xl max-w-sm w-full border border-slate-200 dark:border-slate-700">
    <p id="custom-modal-msg" class="text-slate-700 dark:text-slate-200 mb-4"></p>
    <button type="button" onclick="hideModal()" class="w-full rounded-lg bg-blue-600 px-4 py-2 text-white hover:bg-blue-700 dark:bg-blue-500 dark:hover:bg-blue-600">OK</button>
  </div>
</div>
<script>
function showModal(msg){ 
    var el=document.getElementById('custom-modal'); 
    document.getElementById('custom-modal-msg').textContent=msg||''; 
    el.classList.remove('hidden'); 
}
function hideModal(){ 
    document.getElementById('custom-modal').classList.add('hidden'); 
}
</script>

</body>
</html>
02-25 13:39

登录 后可以评论

Comments

登录 后可以评论