2015-07-20 98 views
-2

我想用HTML和Javascript製作應用程序。我不是這些人的主人。所以我需要一點幫助。應用HTML和JavaScript應用程序

enter image description here

的圖像現在我想的是,當我會點擊橙色區域內的任何地方在中間的數量將增加1我怎樣才能做到這一點使用JavaScript。我的代碼如下:

<html> 
 

 
<head> 
 
    <title>Tabjih</title> 
 
    <style> 
 
    html, 
 
    body, 
 
    .container { 
 
     height: 100%; 
 
     margin: 0; 
 
     padding: 0; 
 
    } 
 
    .container { 
 
     display: flex; 
 
     align-items: center; 
 
     justify-content: center; 
 
     background-color: orange; 
 
    } 
 
    p { 
 
     font-size: 200px; 
 
    } 
 
    </style> 
 
</head> 
 

 
<body> 
 
    <div class="container"> 
 
    <p id="text">0</p> 
 
    </div> 
 
</body> 
 

 
</html>

請給我建議的JavaScript添加到這個實現西隧我想需要的代碼。使用addEventListener

  • container元件上

  • +0

    試試這個鏈接它會幫助你.. http://stackoverflow.com/questions/3076679/javascript-event-registering-without-using -jquery – MPG

    回答

    0
    1. 綁定click事件偵聽從text元件
    2. 值投射到integer使用parseInt()
    3. 增量由一個
    4. 更新值獲取當前值的值在text元素

    document.addEventListener("DOMContentLoaded", function() { 
     
        document.getElementById('container').addEventListener('click', function() { 
     
    
     
        // Get the current value from the element 
     
        var value = parseInt(this.innerText, 10) || 0; 
     
    
     
        // increment the value by one, and update it in DOM 
     
        document.getElementById('text').innerText = ++value; 
     
    
     
        return false; 
     
        }); 
     
    });
    html, 
     
    body, 
     
    .container { 
     
        height: 100%; 
     
        margin: 0; 
     
        padding: 0; 
     
    } 
     
    .container { 
     
        display: flex; 
     
        align-items: center; 
     
        justify-content: center; 
     
        background-color: orange; 
     
    } 
     
    p { 
     
        font-size: 200px; 
     
    }
    <html> 
     
    
     
    <head> 
     
        <title>Tabjih</title> 
     
    </head> 
     
    
     
    <body> 
     
        <div id="container" class="container"> 
     
        <p id="text">0</p> 
     
        </div> 
     
    </body> 
     
    
     
    </html>

    +0

    爲什麼選擇Downvote?有什麼可以改進? – Tushar

    +0

    這真的是我清除步驟後發現的最佳答案。謝謝@Tushar。但你能再幫我一次嗎?其實我並不是很瞭解HTML,所以。當我點擊橙色區域時,它會增加,但有時會選擇文本。我怎樣才能阻止這件事? –

    +0

    @AbeerHussain你不能,這是瀏覽器的默認行爲。你至少可以在事件處理程序中使用'return false'。 – Tushar

    0
    document.getElementsByClassName("container")[0].addEventListener("click",function(){ 
    
    document.getElementById('text').innerHTML = parseInt(document.getElementById('text').innerHTML)+1; 
    }); 
    

    http://jsfiddle.net/s6qc2w3g/12/

    相關問題