简体   繁体   English

如何在段落中随机化字间距?

[英]How to randomise word spacing in a paragraph?

I'm trying to make a panel of words that are distributed unevenly. 我正在尝试制作一组​​分布不均匀的单词。

Here's a very basic sample image: 这是一个非常基本的示例图像:

随机字面板

Using text-align and word-spacing I have come close.. 使用文本对齐和单词间距我已经接近了..

 body { width: 500px; margin: 50px auto 0; } p { background: lightgrey; padding: 2em; font-size: 2em; font-family: sans-serif; word-spacing: 2em; text-align: center; } p span { font-size: 1em; color: white; } 
 <p>one two three four five six seven eight nine ten eleven twelve thirteen fourteen <span>fifteen</span> sixteen seventeen eighteen nineteen twenty</p> 

However I'd like to randomise the spacing between words. 但是我想随机化单词之间的间距。 Is this possible with CSS? 这可能与CSS有关吗? I'm open to changing the HTML, but these panels are dynamically generated and could have any number of words. 我愿意改变HTML,但这些面板是动态生成的,可以包含任意数量的单词。

Any suggestions? 有什么建议?

Codepen for those who prefer Codepen适合那些喜欢的人

Use JS to generate random position on page. 使用JS在页面上生成随机位置。 I made simply random position, you can use more complex algorithm 我做了简单的随机位置,你可以使用更复杂的算法

 $(document).ready(function() { var texts = $('p').text().split(' '); $('p').text(''); $.each(texts, function() { $('p').append( $('<span>', { text: this, "class": this == 'fifteen' ? 'active' : '', css: { left: Math.floor(Math.random() * $('p').width()), top: Math.floor(Math.random() * $('p').height()), fontSize: Math.floor(Math.random() * 20) + 10 } }) ); }); }); 
 p { width: 100%; height: 400px; position: relative; } p span { position: absolute; font-size: 18px; color: #555; } p span.active { color: #00aaff; font-weight: bold; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen twenty</p> 

One option is to use white-space: pre-wrap on your element and js to generate random number of white-spaces between each word. 一种选择是使用white-space: pre-wrap元素和js以在每个单词之间生成随机数量的空格。

 var min = 1; var max = 15; var newText = $('p').html().replace(/\\s/g, function() { return " ".repeat(parseInt(Math.random() * (max - min) + min)) }); $('p').html(newText) 
 body { width: 500px; margin: 50px auto 0; } p { background: lightgrey; padding: 2em; font-size: 1.5em; font-family: sans-serif; text-align: center; white-space: pre-wrap; } p span { font-size: 1em; color: white; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>one two three four five six seven eight nine ten eleven twelve thirteen fourteen <span>fifteen</span> sixteen seventeen eighteen nineteen twenty</p> 

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

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