1. 程式人生 > >JS 清除DOM 中空白元素節點

JS 清除DOM 中空白元素節點

OS 空白節點 arc nod eval text document 元素節點 IT

HTML中的空白節點會影響整體的HTML的版面排榜

例如:

技術分享圖片

制作百度首頁時,兩個input之間的空白節點將本來是要整合在一起的搜索欄硬是把按鈕和搜索框分離出現好醜的間隙

這時我們就可以用js清除這個空白格

下面是HTML的代碼

<form id="fm" name="f" action="post" >
            <span class="search_box">
                <input name="s_r" type="text" maxlength="255" class="s_r" id="s_r" >
                <
span class="search_box_btn"></span> </span> <span class="search_btn"> <input type="submit" name="search" id="search" class="s_btn" value="百度一下"> </span> </form>

css代碼

form{
    position: relative;
}

.search_box
{ display: inline-block; width: 539px; height: 34px; border: 1px solid #b6b6b6; border-width: 1px; border-style:solid ; vertical-align: top; border-color:#b8b8b8 transparent #ccc #b8b8b8; position: relative; } .s_r{ width: 500px; height: 22px; font: 16px arial
; line-height: 22px; margin: 6px 0 0 7px; } .search_box_btn{ position: absolute; width: 18px; height: 16px; background: #fff url(../image/search_box_btn.png) no-repeat; top: 50%; margin-top: -8px; cursor: pointer; right: 11px; } .search_btn{ display: inline-block; } .s_btn{ width: 100px; height: 36px; color: #fff; border-bottom: 1px solid #2d78f4; background: #3385ff; }

js清除節點,為了重復利用,可以將它包裝成一個函數:

 function cleanWhitespace(element)   
    {   
        for(var i=0; i<element.childNodes.length; i++)   
        {   
            var node = element.childNodes[i];   
            if(node.nodeType == 3 && !/\S/.test(node.nodeValue))   
            {   
                node.parentNode.removeChild(node);   
            }   
        }   
    }  

處理節點:在之後加個 cleanWhitespace(document.getElementById("fm")

問題就解決了,嘻嘻

技術分享圖片

JS 清除DOM 中空白元素節點