我有一个很长的预阻塞,我想让它在移动浏览器中查看,比如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
如何制作wordwrap,但保留缩进?
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; }
输出: