我有一个很长的 pre block ,我希望它在移动浏览器中查看,例如 iPhone
例如
a very long pre block start here here here here here here here here here here
2nd line with intent
3rd line with intent
如何制作自动换行,但保留缩进?
e.g.
a very long pre block start here here here here here here
here here here here
2nd line with intent
3rd line with intent
我不想在移动设备上使用滚动条,所以最好有一些方法来自动换行句子。
我尝试过的最相似的方法是使用CSS
pre {
white-space: pre-line;
}
但并不完全如上所示。
最佳答案
这是一种使用 Javascript 实现的方法。这通过 <pre>
并将每个部分包装在 <div>
中与 padding-left
等于缩进的空格数。在演示中,我制作了 <pre>
的大小iPhone 屏幕的大小来演示包装。
脚本:
var pre = document.getElementById( 'pre' ),
sections = pre.textContent.trim().split( '\n' ),
paddingPerChar = 9;
for( var index=0, html='', padding=0; index < sections.length; index++ ) {
padding = ( sections[index].length - sections[index].trim().length ) * paddingPerChar;
html += '<div style="padding-left:' + padding + 'px;">' + sections[index].trim() + '</div>';
};
pre.innerHTML = html;
HTML:
<pre id="pre">
1. a very long pre block start here here here here here here here here here here
A. 2nd line with indent long pre block start here here here here here here here here here
a. 3rd line with indent
B. 4th line th indent long pre block start here here here here here here here her
C. 5th line
2. 6th Line
</pre>
CSS:
pre {
border: 1px solid black;
height: 460px;
width: 320px;
white-space:pre-wrap;
}
输出:
关于javascript - 如何格式化适合宽度受限设备(如 iPhone)的长 <pre> HTML block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8652668/