js:原生封装setCss(三个参数是设置,设置行间属性curEle.style[attr]=val)

537 阅读1分钟
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>4.setCss</title>
    <style>
        html,body,div{
            margin: 0;
            padding: 0;
        }
        #parent{
            width: 200px;
            height: 200px;
            background: greenyellow;
        }
        #box{
            width: 100px;
            height: 100px;
            background: red;
        }
    </style>
</head>
<body>
<div id="parent">
<div id="box">点me</div>
</div>
<script>
 var oParent=document.getElementById('parent');
 var oBox=document.getElementById('box');
 oBox.onclick=function(){
      setCss(oParent,'width',400);
      setCss(oBox,'height',600);
      setCss(oParent,'position','relative');
      setCss(oBox,'position','absolute');
      setCss(oBox,'margin',10);
      setCss(oBox,'padding',10);
      setCss(oBox,'top',20);
      setCss(oBox,'left',30);
 };
 var val;
 function setCss(curEle,attr,val){
          var reg=/^(width|height|margin|padding|top|right|bottom|left|font-size|opacity|float|position)$/;
          if(reg.test(attr)){
             if(typeof val==='number'){
                val+='px';
             }
          }
          curEle.style[attr]=val;
 }
</script>
</body>
</html>