js 控制css

原创 2019-01-04 15:44:55 369
摘要:<!DOCTYPE html><head><meta charset="utf-8"><style type="text/css"> #fdivtest { width: 100px; height: 100px; background-color: green; }</style><scr

<!DOCTYPE html>

<head>

<meta charset="utf-8">

<style type="text/css">

#fdivtest

{

width: 100px; height: 100px; background-color: green;

}

</style>

<script type="text/javascript">

var desdiv;

function showTime(){

    

nowtime=new Date();

    

year=nowtime.getFullYear();

    

month=nowtime.getMonth()+1;

    

date=nowtime.getDate();

    

document.getElementById("mytime").innerText=year+"年"+month+"月"+date+" "+nowtime.toLocaleTimeString();

}


window.onload = function ()

{

desdiv = window.document.getElementById("fdivtest");

}

//setInterval("showTime()",1000);


   function changecss(vpara)

   {

       // alert(desdiv.innerText);

        //alert(desdiv.style.width);

    switch (vpara)

    {

    case 0:

    //desdiv.style.width = "300px;";

    desdiv.style.cssText='width:300px;';

    break;


    case 1:

    desdiv.style.cssText='height:300px;';

    break;  


    case 2:

        //desdiv.style.setProperty('backgroundColor', 'blue', 'important');


    desdiv.style.cssText='background-color: blue';

    break;


        case 3:

        //desdiv.style.setProperty('backgroundColor', 'blue', 'important');


    desdiv.style.cssText= "";

    break; 



        case 4:

        //desdiv.style.setProperty('backgroundColor', 'blue', 'important');


    desdiv.style.cssText= "display: none";

    break;   



        case 5:

        //desdiv.style.setProperty('backgroundColor', 'blue', 'important');


    desdiv.style.cssText= "display: block";

    break;   

    }


   

   }

   function aa() {

       var oStyle = desdiv.currentStyle? desdiv.currentStyle : window.getComputedStyle(desdiv, null); 

    alert(oStyle.getPropertyValue("width"));

    var width = desdiv.style.width;

       // alert(width);

    //desdiv.style.width = "300px;";

    desdiv.style.cssText='width:300px;'

   }

</script>


</head>


<body>

<div id="fdivtest" >

asdfasdf

</div>

<input type="button"  onclick="changecss(0)" value="变宽">

<input type="button"  onclick="changecss(1)" value="变高">

<input type="button"  onclick="changecss(2)" value="变背景色">

<input type="button"  onclick="changecss(3)" value="重置">

<input type="button"  onclick="changecss(4)" value="隐藏">

<input type="button"  onclick="changecss(5)" value="显示">


<span id="mytime"></span>


</body>


</html>


批改老师:天蓬老师批改时间:2019-01-04 16:05:28
老师总结:desdiv = window.document.getElementById("fdivtest"); 不要这样创建变量, 一定要在前面添加var或者 let / const, 这样才能与一个作用域进行绑定,否则就直接绑定到全局了

发布手记

热门词条