HTML5中的可逆卡片使用Javascript

时间:2018-04-06 19:02:58

标签: javascript onclick

我希望您帮助我简化我的代码或为我创建的应用程序构建一个更短的javascript代码,以进入编程世界。 (我真的觉得很新秀)。它包含一些卡片,当用户点击这些卡片时会更改其内容(文本)。

很抱歉,如果代码非常糟糕。我自己开始学习。 很多人都感谢你的答案。

这里的代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" width="device-width, initial-scale=1.0">
<style>



body{background-color:lightblue;
}
    #demo, #demo2{
        padding:20px 3px;
        display:inline;
        margin-top:2000px;
        border-radius:20px;

    }

    #demo:focus, #demo2:focus{
        outline:0px;
    }

    section{
        margin:auto;
        padding-top:50px;
        padding-bottom:50px;
        width:500px;
    }


</style>

</head>
<body>

<section>

<div id="demo" tabindex="-1" onblur="myfirstblurfunction()">Card1</div>
<div id="demo2" tabindex="-1" onblur="mysecondblurfunction()">Card2</div>
<script>





//function



var timesClicked1= 0;

document.getElementById("demo").onclick=function() {myFunction1()};

function myFunction1(){
timesClicked1++;



//If the user clicks once
if(timesClicked1==1){
document.getElementById("demo").style.backgroundColor="orange";
}


//If the user clicks odd times but not the first

else if(timesClicked1%2!==0 && timesClicked1!==1){
document.getElementById("demo").innerHTML="Card1";
document.getElementById("demo").style.backgroundColor="orange";
document.getElementById("demo").style.border="none";


}


//If the user clicks even times
else{
document.getElementById("demo").innerHTML="King";
document.getElementById("demo").style.backgroundColor="lightblue";
document.getElementById("demo").style.border="solid";

}

}



//When the user clicks outside the element, returns to the initial state
function myfirstblurfunction(){
document.getElementById("demo").innerHTML="Card1";
document.getElementById("demo").style.backgroundColor="lightblue";
document.getElementById("demo").style.border="none";


return timesClicked1=0;

}




//function 2 (It's the same, but with -Card2-Queen-)


var timesClicked2 = 0;

document.getElementById("demo2").onclick=function() {myFunction2()};

function myFunction2(){
timesClicked2++;

if(timesClicked2==1){
document.getElementById("demo2").style.backgroundColor="orange";
}

else if(timesClicked2 %2!==0 && timesClicked2!==1){
document.getElementById("demo2").innerHTML="Card2";
document.getElementById("demo2").style.backgroundColor="orange";

}
else{
document.getElementById("demo2").innerHTML="queen";
document.getElementById("demo2").style.backgroundColor="lightblue";

document.getElementById("demo2").style.border="solid";
}

}

function mysecondblurfunction(){
document.getElementById("demo2").innerHTML="Card2";
document.getElementById("demo2").style.backgroundColor="lightblue";
document.getElementById("demo2").style.border="none";

return timesClicked2=0;

}
</script>
</section>
</body>
</html>

0 个答案:

没有答案