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;
        }
    }

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM