分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 网页技术

JS 清除DOM 中空白元素节点

发布时间:2023-09-06 01:52责任编辑:沈小雨关键词:DOM

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 中空白元素节点

原文地址:https://www.cnblogs.com/masanhe/p/8989727.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved