下面的代码片段允许您动态地定位文本块内的每隔一行.以下是实现这一目标的合乎逻辑的步骤:
- 将每个单词放在
<span>
个标签中.
- 删除旧的段落文本并添加
<span>
个标签.
- 确定每一行上有哪些
<span>
个标记.
- 为每行创建一个
<p>
标记,并在其中添加每行的<span>
标记.
- 将这
<p>
个标签加回<div>
.
我把scaleX
和scaleY
都取反了,以获得所需的文本结果.
确保内容使用率达到text-align: center
也是关键.
document.addEventListener("DOMContentLoaded", function() {
wrapWordsInSpan("boustrophedon");
wrapLinesInP("boustrophedon");
});
function wrapWordsInSpan(divId) {
var div = document.getElementById(divId);
var words = div.innerText.split(/\s+/);
div.innerHTML = "";
words.forEach(function(word) {
var span = document.createElement("span");
span.textContent = word + " ";
div.appendChild(span);
});
}
function wrapLinesInP(divId) {
var div = document.getElementById(divId);
var spans = div.getElementsByTagName("span");
var lines = {};
for (var i = 0; i < spans.length; i++) {
var span = spans[i];
var offsetTop = span.offsetTop;
if (!lines[offsetTop]) {
lines[offsetTop] = [];
}
lines[offsetTop].push(span);
}
for (var line in lines) {
var p = document.createElement("p");
lines[line].forEach(function(span) {
p.appendChild(span);
});
div.appendChild(p);
}
}
#boustrophedon p {
text-align: center;
}
#boustrophedon p:nth-child(even) {
transform: scaleY(-1);
transform: scaleX(-1);
}
<div id="boustrophedon">
Cheese on toast port-salut manchego. Cheesy grin taleggio cheddar who moved my cheese bocconcini who moved my cheese goat st. agur blue cheese. Bocconcini cottage cheese cheesecake fromage frais edam cut the cheese croque monsieur cheese and wine. Red
leicester cheese triangles chalk and cheese queso mascarpone cauliflower cheese airedale cheese triangles. Cheeseburger. Parmesan swiss red leicester. Smelly cheese pecorino brie manchego airedale monterey jack stilton camembert de normandie. Smelly
cheese smelly cheese cheese on toast edam cheese and biscuits melted cheese taleggio edam. Cottage cheese. Cut the cheese cut the cheese croque monsieur. Monterey jack smelly cheese pepper jack cheeseburger cheese and wine cottage cheese pepper jack
lancashire. Pepper jack emmental rubber cheese cheesy grin stinking bishop port-salut airedale dolcelatte. Melted cheese pecorino jarlsberg swiss roquefort paneer cow cheesy feet. When the cheese comes out everybody's happy st. agur blue cheese jarlsberg
babybel.
</div>