Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Details

Privacy

Go PRO Window blinds lowered to protect code. Code Editor with window blinds (raised) and a light blub turned on.

Keep it secret; keep it safe.

Private Pens are hidden everywhere on CodePen, except to you. You can still share them and other people can see them, they just can't find them through searching or browsing.

Upgrade to PRO

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

Template

Make Template?

Templates are Pens that can be used to start other Pens quickly from the create menu. The new Pen will copy all the code and settings from the template and make a new Pen (that is not a fork). You can view all of your templates, or learn more in the documentation.

Template URL

Any Pen can act as a template (even if you don't flip the toggle above) with a special URL you can use yourself or share with others. Here's this Pen's template URL:

Screenshot

Screenshot or Custom Thumbnail

Screenshots of Pens are shown in mobile browsers, RSS feeds, to users who chose images instead of iframes, and in social media sharing.

This Pen is using the default Screenshot, generated by CodePen. Upgrade to PRO to upload your own thumbnail that will be displayed on previews of this pen throughout the site and when sharing to social media.

Upgrade to PRO

HTML

              
                <head>
    <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
</head>
<body>
    <div class="calculator">
        <div class="top">
            <div class="temp"><div></div></div>
            <div class="input"><div>0</div></div>
        </div>
        <div class="main">
            <div>
                <a href="#" class="number">7</a>
                <a href="#" class="number">8</a>
                <a href="#" class="number">9</a>
                <a href="#" class="operator"> ÷ </a>
            </div>
            <div>
                <a href="#" class="number">4</a>
                <a href="#" class="number">5</a>
                <a href="#" class="number">6</a>
                <a href="#" class="operator"> × </a>
            </div>
            <div>
                <a href="#" class="number">1</a>
                <a href="#" class="number">2</a>
                <a href="#" class="number">3</a>
                <a href="#" class="operator"> + </a>
            </div>
            <div>
                <a href="#" class="number">0</a>
                <a href="#" class="number">00</a>
                <a href="#" class="number">.</a>
                <a href="#" class="operator"> − </a>
            </div>
            <div>
                <a href="#" class="allClear">AC</a>
                <a href="#" class="back">⌫</a>
                <a href="#" class="equal">=</a>
            </div>
        </div>
    </div>
    <script src="js/all.js"></script>
</body>
              
            
!

CSS

              
                *, *:before, *:after{
    box-sizing: border-box;
}
body{
    font-family: 'Roboto', sans-serif;;
    background: #E8E8E8;
    padding: 100px;
}
.calculator{
    width: 350px;
    margin: 0 auto;
}
.top{
    background: #041936;
    padding: 16px 20px 8px 20px;
    border-radius: 20px 20px 0px 0px;
}
.temp{
    width: 310px;
    height: 19px;
    font-size: 16px;
    color: #00C4FF;
    text-align: right;
    line-height: 19px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
}
.temp div{
    white-space: nowrap;
}
.input{
    color: #FFFFFF;
    text-align: right;
    line-height: 66px;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    width: 310px;
    height: 66px;
}
.input div{
    font-size: 56px;
}
.main{
    background: #072144;
    border-radius: 0px 0px 20px 20px;
    padding: 16px 8px;
    display: flex;
    flex-direction: column;
}
.main div{
    display: flex;
    justify-content: space-between;
    margin-bottom: 16px;
}
.main div:last-child{
    margin-bottom: 0px;
}
.main div a{
    color:#FFFFFF;
    font-size: 24px;
    text-decoration: none;
}
.number{
    font-weight: 300;
}
.number, .operator, .allClear, .back{
    width: 72px;
    height: 64px;
    text-align: center;
    line-height: 64px;
    border-radius: 16px;
}
.number:hover, .operator:hover{
    background: #6C00FF;
}
.operator{
    background: #041936;
    border-radius: 16px;
    font-weight: 500;
}
.main div .allClear, .main div .back{
    color: #00C4FF;
    font-weight: 500;
}
.operator:hover, .main div .allClear:hover, .main div .back:hover{
    background: #00C4FF;
    color: #fff;
}
.back{
    padding-right: 6px;
}
.equal{
    width: 155px;
    height: 64px;
    padding-right: 30px;
    line-height: 64px;
    text-align: right;
    background: linear-gradient(to right, #00C4FF, #6C00FF);
    border-radius: 16px;
    font-weight: 500;
}
.equal:hover{
    background: linear-gradient(to right, #6C00FF , #00C4FF);    
}
              
            
!

JS

              
                let temp = document.querySelector('.temp div');
let input = document.querySelector('.input div');
let button = document.querySelectorAll('.main a');
let tempText = '';
let resultText = '';
let isOutcome = false;   // 記錄是否按下 = 鍵
let isOperator = true;  // 記錄算式結尾是否為運算符
let size = 56;  // 初始 input 文字大小

function mainCalc(e){
    e.preventDefault();
    switch (e.target.className) {
        case 'number':
            dealWithNumber(e);
            break;
        case 'operator':
            dealWithOperator(e);
            break;
        case 'allClear':
            allClear();
            break;
        case 'back':
            backspace();
            break;
        case 'equal':
            getOutcome();
            break;
    }
}

function dealWithNumber(e){
    let text = e.target.textContent;
    if (isOutcome)  allClear();  // 如果剛才才按過 = 鍵,則初始化
    if (isOperator)  inputText = '';  // 初始或如果剛才才按過 operator
        
    switch (text) {
        case '0':
            dealWithZero(text);
            break;
        case '00':
            dealWithZero(text);
            break;
        case '.':
            dealWithDot();
            break;
        default:
            if(input.innerHTML === '0'){
                inputText = '' + text;
                if(tempText.endsWith('0')){
                    tempText = tempText.slice(0, -1) + text;
                } else {
                    tempText += text;
                }           
            } else {
                inputText += text;
                tempText += text;
            }
            break;
    }
    input.innerHTML = addComma(inputText);
    temp.innerHTML = addComma(tempText);
    isOperator = false;
    resizeText();
}

function dealWithZero(text){
    if (isOperator || input.innerHTML === '0'){
        inputText = '0';
        if(tempText.endsWith('0')){
            tempText += '';
        } else {
            tempText += '0';
        }
    } else {
        inputText += text;
        tempText += text;
    }
    return inputText, tempText;
}

function dealWithDot(){
    if(inputText.includes('.')){
        inputText += '';
        tempText += '';
    } else {
        if (isOperator){
            inputText = '0.';
            tempText += '0.';
        } else {
            inputText += '.';
            tempText += '.';
        }
    }
}

function dealWithOperator(e){
    let text = e.target.textContent;
    if (isOperator) return;
    if (tempText.endsWith('.')) {
        tempText = tempText.slice(0, -1);
    }
    tempText += text;
    temp.innerHTML = tempText;
    isOperator = true;
    isOutcome = false;
}

function backspace(){
    if (isOutcome) {
        input.innerHTML = 0;
        isOutcome = false;
    }

    if (tempText.endsWith(' ')) {  // 如果以空格結尾,表示是 operator
        tempText = tempText.slice(0, -3);
        isOperator = false;
    } else {
        tempText = tempText.slice(0, -1);
        inputText = inputText.slice(0, -1);
    }

    temp.innerHTML = addComma(tempText);
    if (tempText.endsWith(' '))  isOperator = true;

    if (inputText.length == 0) {
        input.innerHTML = 0;
    } else {
        input.innerHTML = addComma(inputText);
    }

    resizeText();
}

function getOutcome(){
    if(isOperator || isOutcome) return;

    let tempTextArray = tempText.replace(/×/g, '*').replace(/÷/g, '/').replace(/−/g, '-').split(' ');  // 將字串中的乘(×)、除(÷)、減(−)以正確的運算子取代,並以空白字元分割存成陣列

    // 將陣列中的字串(或數字)從左至右一次拿兩個出來計算,先乘除後加減
    for(let i = 0; i < tempTextArray.length; i += 2){
        let num1, num2, answer;
        if (tempTextArray.includes('*') || tempTextArray.includes('/')){
            switch (tempTextArray[i + 1]){
                case '*':
                    num1 = tempTextArray[i];
                    num2 = tempTextArray[i + 2];
                    answer = calc(num1, num2, '*');
                    tempTextArray.splice(i, 3, answer);
                    i -=2;
                    break;
                case '/':
                    num1 = tempTextArray[i];
                    num2 = tempTextArray[i + 2];
                    answer = calc(num1, num2, '/');
                    tempTextArray.splice(i, 3, answer);
                    i -= 2;
                    break;
            }
        } else {
            i = 0;  // 重新計算 i 
            switch (tempTextArray[i + 1]){
                case '+':
                    num1 = tempTextArray[i]; 
                    num2 = tempTextArray[i + 2];
                    answer = calc(num1, num2, '+');
                    tempTextArray.splice(i, 3, answer);
                    i -= 2;
                    break;
                case '-':
                    num1 = tempTextArray[i]; 
                    num2 = tempTextArray[i + 2];
                    answer = calc(num1, num2, '-');
                    tempTextArray.splice(i, 3, answer);
                    i -= 2;
                    break;
            }
        }
    }

    let outcome = tempTextArray.toString();
    if (isNaN(outcome) || outcome == 'Infinity' || outcome == '-Infinity') {
        input.innerHTML = 0;
        temp.innerHTML = 'Error';
    } else {
        input.innerHTML = addComma(outcome);
        temp.innerHTML += ' = ';
    }

    isOutcome = true;
    resizeText();
}

function allClear(){
    tempText = '';
    temp.innerHTML = tempText;
    inputText = '';
    input.innerHTML = 0;
    input.style.fontSize = '56px';
    isOutcome = false;
    isOperator = true;
}

// 小數點前增加千分位
function addComma(str){
    let parts = str.split('.');
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    return parts.join('.');
}

// 縮放字型大小
function resizeText(){
    let inputWidth = input.scrollWidth;
    let inputParentWidth = input.parentElement.clientWidth;
    let scalePercent = inputParentWidth / inputWidth;
    size *= scalePercent;
    if (size > 56)  size = 56;
    input.style.fontSize = size + 'px';
}

// 浮點數的運算:先將浮點數轉換成整數再計算,計算完再轉換回浮點數
// 參考文章 https://kknews.cc/tech/4q42eeq.html
function calc(num1, num2, operator){
    let point1, point2, m, n;  // point 為 num 小數點後的位數

    if (num1.toString().includes('.')) {
        point1 = num1.toString().split('.')[1].length;
    } else {
        point1 = 0;
    }
    if (num2.toString().includes('.')) {
        point2 = num2.toString().split('.')[1].length;
    } else {
        point2 = 0;
    }

    switch (operator) {
        case '+':
            m = Math.pow(10, Math.max(point1, point2));
            return Math.round(num1 * m + num2 * m) / m;
        case '-':
            m = Math.pow(10, Math.max(point1, point2));
            n = (point1 >= point2)? point1: point2;
            return (Math.round(num1 * m - num2 * m) / m).toFixed(n);
        case '*':
            num1 = num1.toString().replace('.', '');
            num2 = num2.toString().replace('.', '');
            return (num1 * num2) / Math.pow(10, (point1 + point2));
        case '/':
            num1 = num1.toString().replace('.', '');
            num2 = num2.toString().replace('.', '');
            return (num1 / num2) * Math.pow(10, (point2 - point1));
    }
}

button.forEach(item => item.addEventListener('click', mainCalc));
              
            
!
999px
Keep friends close and formatters closer.

Console