简体   繁体   English

使用javascript处理内联块空间

[英]Handling inline-block spaces with javascript

We all know the ages old problem with white spaces between inline-block elements. 我们都知道内联块元素之间存在空白的古老问题。 For example: 例如:

 .wrapper div {width:100px; height:30px; display:inline-block; border:1px solid #333;} 
 <div class="wrapper"> <div></div> <div></div> <div></div> <div></div> </div> 

The best solution in my opinion is to remove any spaces between the elements: 我认为最好的解决方案是删除元素之间的任何空格:

 .wrapper div {width:100px; height:30px; display:inline-block; border:1px solid #333;} 
 <div class="wrapper"> <div> </div><div> </div><div> </div><div> </div> </div> 

Can we do this on a ready HTML with javascript/jQuery, like adding a script to the first snippet to behave like the second one? 我们可以在具有javascript / jQuery的现成HTML上执行此操作吗,例如向第一个代码段添加脚本以使其表现得像第二个代码一样? Some sort of a $('.wrapper').minify(); 某种$('.wrapper').minify(); function. 功能。

EDIT 编辑

Someone suggested a possible duplicate with How to minify HTML with CSS and Javascript? 有人建议使用“ 如何使用CSS和Java脚本最小化HTML”进行重复 . That question is about reducing page size by editing files on server side. 这个问题是关于通过在服务器端编辑文件来减小页面大小。 Here I'm looking for a solution that minifies a specific element after the content is transferred, without editing the html files. 在这里,我正在寻找一种解决方案,该解决方案可以在内容传输后缩小特定元素,而无需编辑html文件。 The problem is not page size, but white spaces in an element. 问题不是页面大小,而是元素中的空格。

Using jQuery you can remove all the textnodes which are children of the wrapper element like 使用jQuery,您可以删除所有属于wrapper元素的子节点的textnode,例如

 $('.wrapper').contents().filter(function() { return this.nodeType == Node.TEXT_NODE; }).remove(); 
 .wrapper div { width: 100px; height: 30px; display: inline-block; border: 1px solid #333; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="wrapper"> <div></div> <div></div> <div></div> <div></div> </div> 

The pure CSS way to do this is to set the font-size of the parent element to 0 纯CSS方法是将父元素的font-size设置为0

 .wrapper div { width:100px; height:30px; display:inline-block; border:1px solid #333; } .wrapper { font-size: 0; } 
 <div class="wrapper"> <div></div> <div></div> <div></div> <div></div> </div> 

If you're worried about the global font-size , then you can try using comments 如果您担心全局font-size ,则可以尝试使用注释

 .wrapper div { width:100px; height:30px; display:inline-block; border:1px solid #333; } 
 <div class="wrapper"> <div></div><!-- --><div></div><!-- --><div></div><!-- --><div></div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM