its*_*_me 6 javascript css pre
是否可以按照在代码编辑器中完成的方式将缩进代码包装在网页上?请参阅下面的屏幕截图比较,以更好地了解我的意思:
pre-wrap 在网页上:

在代码编辑器中包装缩进行:

我所暗示的是,即使在包装后,缩进的行也会保持缩进.这似乎不会发生在网页上.有没有这样做的CSS属性?(JavaScript也可以.)
注意:我不是在谈论代码突出显示.这是关于包裹线的缩进.
如果这很重要 - 这就是我在网页上显示代码块的方式:
<pre><code>if ( is_page() && $post->post_parent ) {
return $post->post_parent;
} else {
return false;
}
</code></pre>
Run Code Online (Sandbox Code Playgroud)
...并且white-space: pre-wrap;样式应用于pre标签.
<div>).marginLeft(或者paddingLeft,如果您愿意)属性设置为单个空间大小和前缀空格数的乘积./**
* Auto-indent overflowing lines
* @author Rob W http://stackoverflow.com/u/938089
* @param code_elem HTMLCodeElement (or any element containing *plain text*)
*/
function autoindent(code_elem) {
// Grab the lines
var textContent = document.textContent === null ? 'textContent' : 'innerText';
var lines = code_elem[textContent].split(/\r?\n/),
fragment = document.createDocumentFragment(),
dummy, space_width, i, prefix_len, line_elem;
// Calculate the width of white space
// Assume that inline element inherit styles from parent (<code>)
dummy = document.createElement('span');
code_elem.appendChild(dummy);
// offsetWidth includes padding and border, explicitly override the style:
dummy.style.cssText = 'border:0;padding:0;';
dummy[textContent] = ' ';
space_width = dummy.offsetWidth;
// Wipe contents
code_elem.innerHTML = '';
for (i=0; i<lines.length; i++) {
// NOTE: All preceeding white space (including tabs is included)
prefix_len = /^\s*/.exec(lines[i])[0].length;
line_elem = fragment.appendChild(document.createElement('div'));
line_elem.style.marginLeft = space_width * prefix_len + 'px';
line_elem[textContent] = lines[i].substring(prefix_len);
}
// Finally, append (all elements inside) the fragment:
code_elem.appendChild(fragment);
}
Run Code Online (Sandbox Code Playgroud)
white-space:pre-wrap)code_elem!)设置为带前缀的空格,然后使用计算宽度.offsetWidth.autoindent函数假定元素的内容是纯文本.