css函數(shù)-設(shè)置或讀取對象的屬性

HTML

<div class="container">
    <div id="box" class="box">
        <div class="btns">
            <button onclick="getStyle()">Get Style</button>
            <button onclick="setStyle()">Set Style</button>
            <button onclick="default_style()">Default Style</button>
        </div>
    </div>
    <div class="box"></div>
</div>

JS

var box = document.getElementById('box');
    function getStyle() {
        var background_color = window.getComputedStyle(box, null).getPropertyValue("background-color");
        var width = window.getComputedStyle(box, null).getPropertyValue("width");
        var height =  window.getComputedStyle(box, null).getPropertyValue("height");
        alert("width: "+width + '\n' +  "height: "+height + '\n' + "background-color: "+background_color)
    }
    function setStyle() {
        box.style.width = 330 + 'px';
        box.style.height = 100 + 'px';
        box.style.backgroundColor = 'rgb(239, 248, 255)';
        box.style.borderColor = 'blue';
        for (var i=0; i<3; i++) {
            document.getElementsByTagName('button')[i].style.backgroundColor = 'blue'
        }
    }
    function default_style() {
        box.style.width = 400 + 'px';
        box.style.height = 200 + 'px';
        box.style.backgroundColor = 'rgb(254, 244, 235)';
        box.style.borderColor = 'orangered';
        for (var i=0; i<3; i++) {
            document.getElementsByTagName('button')[i].style.backgroundColor = 'orangered'
        }
    }

getComputedStyle方法給出應(yīng)用活動樣式表后的元素的所有CSS屬性的值,返回CSSStyleDeclaration表示一個(gè)css屬性鍵值對的集合,getPropertyValue是其的方法之一,返回屬性值,以下示例返回的就是屬性值

    var style1 = getComputedStyle(target, null).getPropertyValue('background-color');

alert()中換行 +'\n'+

這個(gè)函數(shù)寫的好,這樣簡單了好多

function css(obj, attr, value)
{
    switch (arguments.length)
    {
        case 2:
            if(typeof arguments[1] == "object")
            {    //二個(gè)參數(shù), 如果第二個(gè)參數(shù)是對象, 批量設(shè)置屬性
                for (var i in attr)obj.style[i] = attr[i]
            }
            else
            {    //二個(gè)參數(shù), 如果第二個(gè)參數(shù)是字符串, 讀取屬性值
                return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr]
            }
            break;
        case 3:
            //三個(gè)參數(shù), 單一設(shè)置屬性
            obj.style[attr] = value;
            break;
        default:
            alert("參數(shù)錯(cuò)誤!")
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容