前端第二周,Javascript--操作元素的css样式

1.操作元素的css样式 ---只能操作行内样式

              //通过今天这种语法操作css样式是,css属性必须要转换成JS的格式

              //如果css属性 是由一个单词构成的,就直接书写即可

              //如果 css属性 中有连接符(-)连接,则需要将连接符后的单词首字母大写连接符去掉

               border-width 写成 borderWidth

               text-align 写成 textAlign

               font-size 写成 fontSize

               animation-timing-function 写成 animationTimingFunction

1.获取:

        //语法:元素对象.style.css属性名

        console.log(oBox.style.width);//'400px'

        console.log(oBox.style.height);//'300px'

        console.log(oBox.style.border);//'10px'

        console.log(oBox.style.borderWidth);//'10px'

        console.log(oBox.style.textAlign);//'center'

3.设置

        //语法:元素对象.style.css属性名 = '属性值';

        oBox.style.height = '200px';

        oBox.style.color = 'blue';

        oBox.style.borderWidth = '#00ff00';

        oBox.style.fontSize = '70px';

2.获取标签的所有样式 --- cssText

        console.log(oBox.style.cssText);

一次设置标签的多个属性样式 --- cssText

   最终只会执行我们一次设置的多个属性的样式

   原本拥有的样式会被重置

        oBox.style.cssText = 'width:100px;height=100px;background-color:yellow;line-height:100px;fon-size:30px';

2.操作元素的css样式 ---操作非行内样式

获取非行内样式:高版本-低版本

   1.针对高版本浏览器:

             语法:getComputedStyle(ele,null/false)['attr'];

                  第一个参数;元素对象(ele)

                  第二个参数:书写null/false即可,不用管

                  中括号中书写:想要获取的css属性名(arrt)  

 var arrtrs1 = getComputedStyle(obox, null)['width'];

        console.log(arrtrs1);// '400px'

        var arrtrs2 = getComputedStyle(obox, null)['height'];

        console.log(arrtrs2);// '400px'

        var arrtrs3 = getComputedStyle(obox, null)['color'];

        console.log(arrtrs3); // 'rgb(0, 128, 0)'

        var arrtrs4 = getComputedStyle(obox, null)['border'];

        console.log(arrtrs4);  // '9.6px solid rgb(154, 205, 50)'

 2.兼容ie6/7/8低版本浏览器:

             语法:ele.currentStyle['arrt'];  

        var attr1 = obox.ariaCurrent['height'];

        console.log('attr1'); // '400px'

        console.log(window.getComputedStyle);

        // 高版本浏览器访问到 getComputedStyle 函数

        // ie6/7/8低版本浏览器访问到 undefined

 

 //封装实现兼容获取非行内样式的方法:

        function getStyle(ele, attr) {

            if (window.getComputedStyle) {

                return getComputedStyle(ele, null)[attr];

            } else {

                return ele.currentSyle[arrt];

            }

        }

        var a = getStyle(obox, 'color');

        console.log(a);//rgb(135, 206, 235)

        var b = getStyle(obox, 'text-align');

        console.log(b);//center

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值