js控制style样式

1、行内样式获取打印出来
2、内嵌和外链的获取不了
<div style="width:200px;height:200px; background: red;"></div>
 var box=document.getElementsByTagName("div")[0];
 console.log( box.style.width)
3、style属性是对象(数组对象)
4、可以索引值取值
console.log(box.style[0]);
5、值是字符串,没有设置值得是“” 空
6、cssText="字符串形式的样式" 可以一次性添加多个样式,修改原有的内嵌样式
box.style.cssText="border:5px solid black; width:400px; height:200px;"

7、opacity 透明度(子元素,文本都会有透明的样式)不兼容ie6-7-8

1
 box.style.opacity="0.2" (值0-1

8、alpha(opacity=20)透明度(只有自己透明)兼容ie

box.style.filter="alpha(opacity=20)" //百分数

9、获取body 

var body=document.body;

隐藏盒子

var box=document.getElementsByTagName("div")[0];
   box.style.cssText="width:200px; height:200px; background:red;";
    //隐藏盒子的方法
     box.onclick=function () {
         this.style.display="none"//常用
         this.style.opacity="0"//常用
         this.style.visibility="hidden";
    }

案例
 
按搜索,然后在按input的时候高亮显示
<div>
    <input type="text" >
    <input type="text">
    <input type="text">
    <input type="text">
    <input type="text">
    <button>搜索</button>
</div>
<script>
丢失鼠标的时候样式消失(工作中经常用到)
    var inpArr=document.getElementsByTagName("input");
    var button=inpArr[inpArr.length-1].nextElementSibling ||inpArr[inpArr.length-1].nextSibling;
    button.onclick=function () {
        for(var i=0; i<inpArr.length; i++){
            //当button按钮被点击以后,所有的input标签被绑定事件,onfocus事件
            inpArr[i].onfocus=function(){
                this.style.border="1px solid red";
                this.style.backgroundColor="#ccc";
            };
            //绑定onblur事件,取消样式
            inpArr[i].onblur=function(){
                this.style.border="";
                this.style.backgroundColor="";
            }
        }
    }
</script>

 

 

各行变色,鼠标移入高亮显示

//需求:让tr各行变色,鼠标放入tr中,高亮显示。
    //1.隔行变色。
    var tbody=document.getElementById("target");
    var trArr=tbody.children;
    for(var i=0; i<trArr.length;i++){
        if(i%2==0){
            trArr[i].style.backgroundColor="#c3c3c3"
        }
    //鼠标进入高亮显示 离开时还原
    //难点:鼠标移开的时候要回复原始颜色。
    //计数器(进入tr之后,立刻记录颜色,然后移开的时候使用记录好的颜色)
        var color="";
        trArr[i].onmouseover=function(){
            color=this.style.backgroundColor;
            this.style.backgroundColor="#fff";
        };
        trArr[i].onmouseout=function () {
            this.style.backgroundColor=color;
        }
    }

 

 

posted @ 2017-09-20 18:23  Me*淡定  阅读(88073)  评论(1编辑  收藏  举报