javascript - 如何格式化适合宽度受限设备(如 iPhone)的长 <pre> HTML block

标签 javascript android iphone html css

我有一个很长的 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;
        }

但并不完全如上所示。

更新:链接: http://pastehtml.com/view/bisxytioa.html

最佳答案

这是一种使用 Javascript 实现的方法。这通过 <pre>并将每个部分包装在 <div> 中与 padding-left等于缩进的空格数。在演示中,我制作了 <pre> 的大小iPhone 屏幕的大小来演示包装。

演示: jsFiddle

脚本:

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;
}

输出:

enter image description here

关于javascript - 如何格式化适合宽度受限设备(如 iPhone)的长 <pre> HTML block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8652668/

相关文章:

javascript - 如何在 JS 中使用动态名称调用函数

javascript - 滚动顶部未到达正确位置

android - 如何在 Instagram 应用程序上实现 View (不在图像上)的模糊/霜/纤维背景效果

iphone - 如何在 Xcode iPhone 应用程序中创建多个页面

javascript - 如何在 iPhone 上拖动 'div' 元素

javascript - WinJS 中未处理的异常

javascript - Accordion 高度问题

android - 硬件后退按钮关闭启用 Tab 的 Ionic 3 应用程序上的应用程序

android - 在 Android 中的布局中屏蔽图像

ios - iPhone (iOS) 上的响应式网站图像变得模糊