1. 程式人生 > >js demo:控制div屬性

js demo:控制div屬性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>控制div屬性</title>
    <style>
    #outer{
        width:500px;
        margin:0px auto;
        padding: 0;
        text-align: center;
    }
    #div1{
        width: 100px;
        height: 100px;
        background-color: black;
        margin: 10px auto;
        display: block;
    }
</style>
<script>
  // elem.style[atter] =value
  //elem的樣式:atter:value;
    var changeStyle =function(elem,atter,value){
        elem.style[atter] =value
        
    };
    window.onload=function(){
        var oBtn = document.getElementsByTagName("input");
        var oDiv = document.getElementById("div1");
        var oAtt = ["width","height","background-color","display","display"];
        var oVal = ["200px","200px","red","none","block"]
        for( var i =0;i<oBtn.length;i++){
            oBtn[i].index=i;
            oBtn[i].onclick=function(){
            // 邏輯與運算  a && b  轉換成布林值運算後進行邏輯與運算  true 執行b,false 執行a
                this.index == oBtn.length-1 && (oDiv.style.cssText="");
                changeStyle(oDiv,oAtt[this.index],oVal[this.index])
            }

        }

    }
</script>
</head>
<body>
    <div id="outer">
        <input type="button" value="變寬">
        <input type="button" value="變高">
        <input type="button" value="變色">
        <input type="button" value="隱藏">
        <input type="button" value="重置">
        <div id="div1"></div>
    </div>
    <audio controls="controls" style="display:none"></audio>
    
</body>
</html>