1. 程式人生 > 實用技巧 >DOM屬性操作和樣式操作

DOM屬性操作和樣式操作

1 屬性操作

1.1 HTML attribute -> DOM property

/* 把HTML的屬性轉化為DOM的屬性 */
---
<div>
    <label for="userName">使用者名稱:</albel>
    <input id="userName" type="text" class="u-txt">
</div>
---
//input--html
id   -->"userName"
type -->"text"
class-->"u-text"
//input--DOM
id   -->"userName"
type -->"text"
className -->"u-txt"

//label--DOM
htmlFor -->"userName"

1.2 通過屬性名訪問修改屬性

---
<div>
    <label for="userName">使用者名稱:</label>
    <input id="userName" type="text" class="u-txt">
</div>
---
var input = document.querySelector('#userName');
//讀取
input.className;//"u-txt"
input["id"];//"userName"
//寫入屬性
input.value = "[email protected]";
input.disabled = true;
//<input id="userName" type="text" class="u-txt" value="[email protected] disabled>
/* 通過屬性名可以設定的屬性型別為 ——>轉換過的實用物件 */
/* 
   className :"u-txt"                   -->String
   maxLength :10                        -->Number
   disabled  :true                      -->Boolean
   onclick   :function onclick(event){} -->Function 
*/

//通過屬性名訪問的特點:通用性不好,會有名字異常;擴充套件性沒有;但設定的直接為實用物件;

1.3 Get/SetAttribute

---
<div>
    <label for="userName">使用者名稱:</label>
    <input id="userName" type="text" class="u-text">
</div>
---
//讀取
/* var attribute = element.getAttribute(attributeName); */
input.getAttribute("class");//"u-txt"
//寫入
/* element.setAttribute(name,value) */
input.setAttribute("value","[email protected]");
//<input id="userName" type="text" class="u-txt" value="[email protected]">
/* 通過get/setAttribute設定的屬性型別為 ——>屬性字串 */
/* 
    class     :"u-txt"    -->String
    maxlength :"10"       -->String
    disabled  :""         -->String
    onclick   :"showSuggest();"
*/

//通過get/setAttribute設定屬性的特點:只能設定字串;但是通用性好;

以上兩種屬性訪問修改方法的使用範例:

---
<div>
    <h2>手機號碼登入</h2>
    <label for="userName">使用者名稱:</label>
    <input id="userName" type="text">
    <label for="secuNum">密碼:</label>
    <input id="secuNum" type="text">
    <button id="logbtn">登入</button>
</div>
---
//讓登入按鈕disabled
button.disabled = true;
button.setAttribute("class","disabled");//Are you sure ?????

1.4 dataset

/* HTMLElement.dataset */
/* data-* 屬性集 */
/* 在元素上儲存資料 */
---
<div id="user" 
  data-id="19910620" 
  data-account-name="LWL" 
  data-name="盧萬林" 
  data-email="[email protected]" 
  data-mobile="15528332669"
>
  LWL
</div>
---
/* div.dataset.
    id          --> "19910620"
    accountName --> "LWL"
    name        --> "盧萬林"
    email       --> "[email protected]"
    mobiel      --> "15528332669"
*/
//功能需求,在-盧萬林-被hover的時候,在名字的右邊出現一張表格,裡面是個人資訊;
//html
<div class="mb-s" id="p3">
<ul id="b434">
    <li id="b434li1" data-id="19910610" data-account-name="LWL" data-name="Adom|Wanlin-Lu"
        data-email="[email protected]" data-mobile="15528332668">Wanlin-Lu</li>
    <li id="b434li2" data-id="18820625" data-account-name="HYJ" data-name="huoyuanjia"
        data-email="[email protected]" data-mobile="18780121320">big brother</li>
</ul>
<div style="display:none" id="card">
    <table>
        <caption id="accountName"></caption>
        <tr><th>name:</th><td id="name"></td></tr>
        <tr><th>email:</th><td id="email"></td></tr>
        <tr><th>tele:</th><td id="mobile"></td></tr>
    </table>
</div>
//css
#card table th,td,caption{
    border:1px solid #888888;
    padding:2px;
    font-size:14px;
}
#card table th{
    color:#444;
}
#p3{
    position:relative;
}
#card{
    position:absolute;
    left:150px;
    top:50px;
}
#card table{
    border-collapse: collapse;
}
//js
function $(id){
    return document.getElementById(id);
}
var b434ul = $("b434");
var lis = b434ul.getElementsByTagName("li");
for(var i=0,li;li=lis[i];i++){
    li.onmouseenter = function(event){
        event = event||window.event;
        var pers = event.target||event.srcElement;
        var data = pers.dataset;

        $("accountName").innerText = data.accountName;
        $("name").innerText = data.name;
        $("email").innerText = data.email;
        $("mobile").innerText = data.mobile;

        $("card").style.display="block";
    };
    li.onmouseleave = function(event){
        $("card").style.display="none";
    };
}

dataset 相容實現

/* dataset 相容實現 */
function dataset(element){
    if(element.dataset){
        return element.dataset;
    }else{
        var attributes = element.attributes;
        var name = [],value = [];
        var obj = {};
        for(var i=0;i<attributes.length;i++){
            if(attributes[i].nodeName.slice(0,5)=="data-"){
                name.push(attributes[i].nodeName.slice(5));
                value.push(attributes[i].nodeValue);
            }
        }
        for(var j=0;j<name.length;j++){
            obj[name[j]] = value[j];
        }
        return obj;
    }
}
//測試dataset(element)
var b434li2 = $("b434li2");
var ss = dataset(b434li2);
console.log(ss);
//DOMStringMap {id: "18820625", accountName: "HYJ", name: "huoyuanjia", email: "[email protected]", mobile: "18780121320"}

2 樣式操作

2.1 CSS-->DOM

//綜合樣式
/* document.styelSheets-->elementsheet(<link-stylesheet>|<style></style>)-->cssRules[i]--->style-->styleName */
---
<style>
    body{margin:20px;}
    p{color:#aaa;line-height:20px;}
</style>
---
//獲取line-height
element.sheet.cssRules[1].style.lineHeight;//"20px"--->這句是有問題的,得不到這樣的結果!!

//行內樣式
/* element.style.styleName */
---
<p style="color:red;font-size:10px;">you are right,I an a paragraph</p>
---

//獲取color
p.style.color;//"red"
//獲取font-size
p.style.fontSize;//"10px"

2.2 更新樣式

方法有兩類、三種:element.style,element.style.cssText更新element的className

---
<input id="userName">
---
//將上面input元素的邊框顏色和文字顏色都設定為red

/* 方法一:element.style */
element.style.borderColor = 'red';
element.styel.color = 'red';
//該方法的問題:更新一個屬性需要一條語句;不是我們熟悉的CSS

/* 方法二:element.style.cssText */
element.style.cssText = "border-color:red;color:red;";
//該方法的問題:和方法一類似,樣式混合在邏輯中;

/* 方法三:更新class */
---css
.invalid{
    border-color:red;
    color:red;
}
---
//給input新增class
element.className += " invalid";//<input id="userName" class="invalid">

應用拓展:換膚

在練習的時候補充具體程式碼,現在只需要瞭解原理即可!
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>換膚</title>
    <link rel="stylesheet" type="text/css" href="base.css">
</head>
<body>
<div class="m-tw clearfix">
    <div class="u-img">
        <img src="res/zhm.jpg">
    </div>
    <div class="txt">
        <h3>張惠妹</h3>
        <p>中國國寶級傳奇天后,被歌迷們親切的稱為‘阿妹’。但是這幾年卻很少看到她的演出了,或許她已經過上了另一種幸福的生活吧?</p>
    </div>
</div>
<div id="button">
    <button id="create0">建立外部樣式表</button>
    <button id="create1">建立內部樣式表</button>
</div>
<script type="text/javascript">
function $(id) {
    return typeof id === "string" ? document.getElementById(id) : id;
}
var Util = (function(document, util) {
    util = util || {};

    util.addEventListener = function(element, type, listener) {
        if (element.addEventListener) {
            element.addEventListener(type, listener, false);
        } else {
            element.attachEvent('on' + type, listener);
        }
    }
    return util;
})(document, Util);

Util.addEventListener($("create0"),'click',createStyleSheet0);
Util.addEventListener($("create1"),'click',createStyleSheet1);
function createStyleSheet0(){
    var link = document.createElement("link");
    link.rel = "stylesheet";
    link.type = "text/css";
    link.href = "skin.summer.css";
    document.getElementsByTagName("head")[0].appendChild(link);
}
function createStyleSheet1(){
    var style = document.createElement("style");
    style.innerText = 'body{background-color: #fefaf7;}\
                        .m-tw .u-img{border-color: #a84c5b;}\
                        .m-tw p{color: #6d3e48;}\
                        .m-tw h3{background-color: red;}\
                        .m-tw h3 a, .m-tw h3 a:hover{color: #fff;}';
    document.getElementsByTagName('head')[0].appendChild(style);
}
</script>
</body>
</html>

2.3 獲取樣式

/* element.style */
---
<input type="text" style="color:red">
---
element.style.color;//'red'
//`element.style`只能獲取元素的行內樣式,而且獲得的還不一定是元素的實際樣式。

/* window.getComputedStyle() */
/* var style = window.getComputedStyle(element[,psedoElt]); */
---html
<input type="text">
---
//獲取input的color
window.getComputedStyle(element).color;//"rgb(0,0,0)"
---html
<input type="text" style="color:red">
---
//獲取input的color
window.getComputedStyle(element).color;//"rgb(255,0,0)"
//window.getComputedStyle是一個CSSStyleDeclaration物件(CSS屬性都列出來了,數量巨大),可以在console中檢視

/* ie9-中使用element.currentStyle */