zoukankan      html  css  js  c++  java
  • js控制style样式

    1、行内样式获取打印出来
    2、内嵌和外链的获取不了
    <div style="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; 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="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;
            }
        }

  • 相关阅读:
    vue中的$nextTick()
    对SPA(单页面应用)的总结
    函数节流和函数防抖
    前端路由
    let、const
    深拷贝与浅拷贝
    小白浅谈Ajax基础
    关于BFC布局的那些事
    关于BFC的那些事
    Sass基础知识及语法
  • 原文地址:https://www.cnblogs.com/wdz1/p/7562975.html
Copyright © 2011-2022 走看看