Javascript 使用 CSS 自动处理 2 列文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3009670/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
flow 2 columns of text automatically with CSS
提问by Joseph Mastey
I have the code similar to the following:
我有类似于以下的代码:
<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<p>This is paragraph 3. Lorem ipsum ... </p>
<p>This is paragraph 4. Lorem ipsum ... </p>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>
I'd like to, without markup if possible, cause this text to flow into two columns (1-3 on the left, 4-6 on the right). The reason for my hesitation to add a column using a <div>is that this text is entered by the client via a WYSIWYG editor, so any elements I inject are likely to be killed later or inexplicably.
如果可能的话,我想在没有标记的情况下使此文本流入两列(左侧 1-3,右侧 4-6)。我之所以犹豫使用 a 添加列的原因<div>是该文本是由客户端通过 WYSIWYG 编辑器输入的,因此我注入的任何元素都可能在以后或莫名其妙地被杀死。
采纳答案by Glennular
Using jQuery
使用 jQuery
Create a second column and move over the elements you need into it.
创建第二列并将您需要的元素移到其中。
<script type="text/javascript">
$(document).ready(function() {
var size = $("#data > p").size();
$(".Column1 > p").each(function(index){
if (index >= size/2){
$(this).appendTo("#Column2");
}
});
});
</script>
<div id="data" class="Column1" style="float:left;width:300px;">
<!-- data Start -->
<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<p>This is paragraph 3. Lorem ipsum ... </p>
<p>This is paragraph 4. Lorem ipsum ... </p>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>
<!-- data Emd-->
</div>
<div id="Column2" style="float:left;width:300px;"></div>
Update:
更新:
OrSince the requirement now is to have them equally sized. I would suggest using the prebuilt jQuery plugins: Columnizer jQuery Plugin
或者因为现在的要求是让它们的大小相同。我建议使用预先构建的 jQuery 插件:Columnizer jQuery Plugin
回答by Glennular
Use CSS3
用 CSS3
.container {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
-webkit-column-gap: 20px;
-moz-column-gap: 20px;
column-gap: 20px;
}
Browser Support
浏览器支持
- Chrome 4.0+ (
-webkit-) - IE 10.0+
- Firefox 2.0+ (
-moz-) - Safari 3.1+ (
-webkit-) - Opera 15.0+ (
-webkit-)
- 铬 4.0+ (
-webkit-) - 浏览器 10.0+
- 火狐 2.0+ (
-moz-) - Safari 3.1+ (
-webkit-) - 歌剧 15.0+ (
-webkit-)
回答by Arve Systad
Automatically floating two columns next to eachother is not currently possible only with CSS/HTML. Two ways to achieve this:
目前仅使用 CSS/HTML 无法自动将两列彼此相邻浮动。实现这一目标的两种方法:
Method 1: When there's no continous text, just lots of non-related paragraphs:
方法1:当没有连续文本时,只有很多不相关的段落:
Float all paragraphs to the left, give them half the width of the containing element and if possible set a fixed height.
将所有段落向左浮动,给它们包含元素宽度的一半,如果可能,设置一个固定的高度。
<div id="container">
<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<p>This is paragraph 3. Lorem ipsum ... </p>
<p>This is paragraph 4. Lorem ipsum ... </p>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>
</div>
#container { width: 600px; }
#container p { float: left; width: 300px; /* possibly also height: 300px; */ }
You can also insert clearer-divs between paragraphs to avoid having to use a fixed height. If you want twocolumns, add a clearer-div between two-and-two paragraphs. This will align the top of the two next paragraphs, making it look more tidy. Example:
您还可以在段落之间插入更清晰的 div 以避免必须使用固定高度。如果您想要两列,请在两两段落之间添加一个更清晰的 div。这将对齐下两个段落的顶部,使其看起来更整洁。例子:
<div id="container">
<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<div class="clear"></div>
<p>This is paragraph 3. Lorem ipsum ... </p>
<p>This is paragraph 4. Lorem ipsum ... </p>
<div class="clear"></div>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>
</div>
/* in addition to the above CSS */
.clear { clear: both; height: 0; }
Method 2: When the text is continous
方法二:当文本是连续的
More advanced, but it can be done.
更高级,但可以做到。
<div id="container">
<div class="contentColumn">
<p>This is paragraph 1. Lorem ipsum ... </p>
<p>This is paragraph 2. Lorem ipsum ... </p>
<p>This is paragraph 3. Lorem ipsum ... </p>
</div>
<div class="contentColumn">
<p>This is paragraph 4. Lorem ipsum ... </p>
<p>This is paragraph 5. Lorem ipsum ... </p>
<p>This is paragraph 6. Lorem ipsum ... </p>
</div>
</div>
.contentColumn { width: 300px; float: left; }
#container { width: 600px; }
When it comes to the ease of use: none of these are really easy for a non-technical client. You might attempt to explain to him/her how to do this properly, and tell him/her why. Learning very basic HTML is not a bad idea anyways, if the client is going to be updating the web pages via a WYSIWYG-editor in the future.
谈到易用性:对于非技术客户来说,这些都不是真的容易。您可以尝试向他/她解释如何正确执行此操作,并告诉他/她原因。无论如何,如果客户将来要通过 WYSIWYG 编辑器更新网页,学习非常基本的 HTML 并不是一个坏主意。
Or you could try to implement some Javascript-solution that counts the total number of paragraphs, splits them in two and creates columns. This will also degrade gracefully for those who have JavaScript disabled. A third option is to have all this splitting-into-columns-action happen serverside if this is an option.
或者您可以尝试实现一些 Javascript 解决方案,该解决方案计算段落总数,将它们分成两部分并创建列。对于那些禁用 JavaScript 的人来说,这也会优雅地降级。如果这是一个选项,第三个选项是让所有这些拆分为列的操作发生在服务器端。
(Method 3: CSS3 Multi-column Layout Module)
(方法三:CSS3多列布局模块)
You might read about the CSS3 way of doing it, but it's not really practical for a production website. Not yet, at least.
您可能会阅读CSS3 的做法,但它对于生产网站来说并不实用。至少还没有。
回答by 99freebies.blogspot.com
Here is an example of a simple Two-column class:
这是一个简单的两列类的示例:
.two-col {
-moz-column-count: 2;
-moz-column-gap: 20px;
-webkit-column-count: 2;
-webkit-column-gap: 20px;
}
Of which you would apply to a block of text like so:
您可以将其中的一部分应用于文本块,如下所示:
<p class="two-col">Text</p>
回答by Abner M
Not an expert here, but this is what I did and it worked
不是这里的专家,但这就是我所做的并且有效
<html>
<style>
/*Style your div container, must specify height*/
.content {width:1000px; height:210px; margin:20px auto; font-size:16px;}
/*Style the p tag inside your div container with half the with of your container, and float left*/
.content p {width:490px; margin-right:10px; float:left;}
</style>
<body>
<!--Put your text inside a div with a class-->
<div class="content">
<h1>Title</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus gravida laoreet lectus. Pellentesque ultrices consequat placerat. Etiam luctus euismod tempus. In sed eros dignissim tortor faucibus dapibus ut non neque. Ut ante odio, luctus eu pharetra vitae, consequat sit amet nunc. Aenean dolor felis, fringilla sagittis hendrerit vel, egestas eget eros. Mauris suscipit bibendum massa, nec mattis lorem dignissim sit amet. </p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer eget dolor neque. Phasellus tellus odio, egestas ut blandit sed, egestas sit amet velit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;</p>
</div>
</body>
</html>
Once the text inside the <p>tags has reached the height of the container div, the other text will flow to the right of the container.
一旦<p>标签内的文本达到容器 div 的高度,其他文本将流向容器的右侧。
回答by Mr. Polywhirl
Below I have created both a static and dynamic approach at columnizing paragraphs. The code is pretty much self-documented.
下面我创建了一种静态和动态方法来对段落进行分栏。该代码几乎是自我记录的。
Foreward
前进
Below, you will find the following methods for creating columns:
下面,您将找到以下创建列的方法:
- Static (2-columns)
- Dynamic w/ JavaScript + CSS (n-columns)
- Dynamic w/ JavaScript + CSS3 (n-columns)
- 静态(2 列)
- 带有 JavaScript + CSS 的动态(n 列)
- 带有 JavaScript + CSS3 的动态(n 列)
Static (2-columns)
静态(2 列)
This is a simple 2 column layout. Based on Glennular's 1st answer.
这是一个简单的 2 列布局。基于Glennular的第一个答案。
$(document).ready(function () {
var columns = 2;
var size = $("#data > p").size();
var half = size / columns;
$(".col50 > p").each(function (index) {
if (index >= half) {
$(this).appendTo(".col50:eq(1)");
}
});
});
.col50 {
display: inline-block;
vertical-align: top;
width: 48.2%;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data" class="col50">
<!-- data Start -->
<p>This is paragraph 1. Lorem ipsum ...</p>
<p>This is paragraph 2. Lorem ipsum ...</p>
<p>This is paragraph 3. Lorem ipsum ...</p>
<p>This is paragraph 4. Lorem ipsum ...</p>
<p>This is paragraph 5. Lorem ipsum ...</p>
<p>This is paragraph 6. Lorem ipsum ...</p>
<p>This is paragraph 7. Lorem ipsum ...</p>
<p>This is paragraph 8. Lorem ipsum ...</p>
<p>This is paragraph 9. Lorem ipsum ...</p>
<p>This is paragraph 10. Lorem ipsum ...</p>
<p>This is paragraph 11. Lorem ipsum ...</p>
<!-- data End-->
</div>
<div class="col50"></div>
Dynamic w/ JavaScript + CSS (n-columns)
带有 JavaScript + CSS 的动态(n 列)
With this approach, I essentially detect if the block needs to be converted to columns. The format is col-{n}. nis the number of columns you want to create.
通过这种方法,我基本上可以检测块是否需要转换为列。格式为col-{n}. n是您要创建的列数。
$(document).ready(function () {
splitByColumns('col-', 4);
});
function splitByColumns(prefix, gap) {
$('[class^="' + prefix + '"]').each(function(index, el) {
var me = $(this);
var count = me.attr("class").split(' ').filter(function(className) {
return className.indexOf(prefix) === 0;
}).reduce(function(result, value) {
return Math.max(parseInt(value.replace(prefix, '')), result);
}, 0);
var paragraphs = me.find('p').get();
me.empty(); // We now have a copy of the children, we can clear the element.
var size = paragraphs.length;
var percent = 1 / count;
var width = (percent * 100 - (gap / count || percent)).toFixed(2) + '%';
var limit = Math.round(size / count);
var incr = 0;
var gutter = gap / 2 + 'px';
for (var col = 0; col < count; col++) {
var colDiv = $('<div>').addClass('col').css({ width: width });
var css = {};
if (col > -1 && col < count -1) css['margin-right'] = gutter;
if (col > 0 && col < count) css['margin-left'] = gutter;
colDiv.css(css);
for (var line = 0; line < limit && incr < size; line++) {
colDiv.append(paragraphs[incr++]);
}
me.append(colDiv);
}
});
}
.col {
display: inline-block;
vertical-align: top;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data" class="col-6">
<!-- data Start -->
<p>This is paragraph 1. Lorem ipsum ...</p>
<p>This is paragraph 2. Lorem ipsum ...</p>
<p>This is paragraph 3. Lorem ipsum ...</p>
<p>This is paragraph 4. Lorem ipsum ...</p>
<p>This is paragraph 5. Lorem ipsum ...</p>
<p>This is paragraph 6. Lorem ipsum ...</p>
<p>This is paragraph 7. Lorem ipsum ...</p>
<p>This is paragraph 8. Lorem ipsum ...</p>
<p>This is paragraph 9. Lorem ipsum ...</p>
<p>This is paragraph 10. Lorem ipsum ...</p>
<p>This is paragraph 11. Lorem ipsum ...</p>
<!-- data End-->
</div>
Dynamic w/ JavaScript + CSS3 (n-columns)
带有 JavaScript + CSS3 的动态(n 列)
This has been derived from on Glennular's 2nd answer. It uses the column-countand column-gapCSS3 rules.
这源自Glennular的第二个答案。它使用column-count和column-gapCSS3 规则。
$(document).ready(function () {
splitByColumns('col-', '4px');
});
function splitByColumns(prefix, gap) {
var vendors = [ '', '-moz', '-webkit-' ];
var getColumnCount = function(el) {
return el.attr("class").split(' ').filter(function(className) {
return className.indexOf(prefix) === 0;
}).reduce(function(result, value) {
return Math.max(parseInt(value.replace(prefix, '')), result);
}, 0);
}
$('[class^="' + prefix + '"]').each(function(index, el) {
var me = $(this);
var count = getColumnCount(me);
var css = {};
$.each(vendors, function(idx, vendor) {
css[vendor + 'column-count'] = count;
css[vendor + 'column-gap'] = gap;
});
me.css(css);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="data" class="col-3">
<!-- data Start -->
<p>This is paragraph 1. Lorem ipsum ...</p>
<p>This is paragraph 2. Lorem ipsum ...</p>
<p>This is paragraph 3. Lorem ipsum ...</p>
<p>This is paragraph 4. Lorem ipsum ...</p>
<p>This is paragraph 5. Lorem ipsum ...</p>
<p>This is paragraph 6. Lorem ipsum ...</p>
<p>This is paragraph 7. Lorem ipsum ...</p>
<p>This is paragraph 8. Lorem ipsum ...</p>
<p>This is paragraph 9. Lorem ipsum ...</p>
<p>This is paragraph 10. Lorem ipsum ...</p>
<p>This is paragraph 11. Lorem ipsum ...</p>
<!-- data End-->
</div>
回答by sjskier
Maybe a slightly tighter version? My use case is outputting college majors given a json array of majors (data).
也许是稍微紧一点的版本?我的用例是根据专业(数据)的 json 数组输出大学专业。
var count_data = data.length;
$.each( data, function( index ){
var column = ( index < count_data/2 ) ? 1 : 2;
$("#column"+column).append(this.name+'<br/>');
});
<div id="majors_view" class="span12 pull-left">
<div class="row-fluid">
<div class="span5" id="column1"> </div>
<div class="span5 offset1" id="column2"> </div>
</div>
</div>
回答by namretiolnave
This solution will split into two columns and divide the content half in one line half in the other.This comes in handy if you are working with data that gets loaded into the first column, and want it to flow evenly every time. :). You can play with the amount that gets put into the first col. This will work with lists as well.
此解决方案将分成两列,并将内容的一半分成一行的一半在另一行中。如果您正在处理加载到第一列中的数据,并希望它每次都均匀流动,这会派上用场。:)。您可以使用放入第一列的数量。这也适用于列表。
Enjoy.
享受。
<html>
<head>
<title>great script for dividing things into cols</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script>
$(document).ready(function(){
var count=$('.firstcol span').length;
var selectedIndex =$('.firstcol span').eq(count/2-1);
var selectIndexafter=selectedIndex.nextAll();
if (count>1)
{
selectIndexafter.appendTo('.secondcol');
}
});
</script>
<style>
body{font-family:arial;}
.firstcol{float:left;padding-left:100px;}
.secondcol{float:left;color:blue;position:relative;top:-20;px;padding-left:100px;}
.secondcol h3 {font-size:18px;font-weight:normal;color:grey}
span{}
</style>
</head>
<body>
<div class="firstcol">
<span>1</span><br />
<span>2</span><br />
<span>3</span><br />
<span>4</span><br />
<span>5</span><br />
<span>6</span><br />
<span>7</span><br />
<span>8</span><br />
<span>9</span><br />
<span>10</span><br />
<!--<span>11</span><br />
<span>12</span><br />
<span>13</span><br />
<span>14</span><br />
<span>15</span><br />
<span>16</span><br />
<span>17</span><br />
<span>18</span><br />
<span>19</span><br />
<span>20</span><br />
<span>21</span><br />
<span>22</span><br />
<span>23</span><br />
<span>24</span><br />
<span>25</span><br />-->
</div>
<div class="secondcol">
</div>
</body>
</html>

