我目前在预编码块中有以下html:
<pre class="prettyprint"><code>
<html>
<body>
<form name="input" action="html_form_action.asp" method="get">
<input type="radio" name="sex" value="male">Male<br>
<input type="radio" name="sex" value="female">Female<br>
<input type="submit" value="Submit">
</form>
<p>If you click the "Submit" button, the form-data will be sent to a page called "html_form_action.asp".</p>
</body>
</html>
</code></pre>
它在html源代码中缩进,以便在文档中获得更好的结构。如何删除前导空格?通过使用javascript还是有更简单的方法。
答案 0 :(得分:33)
The question asks if there's a JavaScript solution or a simpler method for removing leading whitespace. There's a simpler method:
CSS
pre, code {
white-space: pre-line;
}
The
white-space
property is used to describe how whitespace inside the element is handled.pre-line
Sequences of whitespace are collapsed.
答案 1 :(得分:5)
我真的很喜欢Homam的想法,但我不得不改变它来处理这个问题:
<pre><code><!-- There's nothing on this line, so the script thinks the indentation is zero -->
foo = bar
</code></pre>
要解决这个问题,我只需要取出第一行,如果它是空的:
[].forEach.call(document.querySelectorAll('code'), function($code) {
var lines = $code.textContent.split('\n');
if (lines[0] === '')
{
lines.shift()
}
var matches;
var indentation = (matches = /^[\s\t]+/.exec(lines[0])) !== null ? matches[0] : null;
if (!!indentation) {
lines = lines.map(function(line) {
line = line.replace(indentation, '')
return line.replace(/\t/g, ' ')
});
$code.textContent = lines.join('\n').trim();
}
});
(我还处理<code>
代码而不是<pre>
代码。)
答案 2 :(得分:4)
您可能只想更改输出方式,但使用JavaScript
非常简单var p = document.querySelector(".prettyprint");
p.textContent = p.textContent.replace(/^\s+/mg, "");
答案 3 :(得分:4)
扩展上述解决方案,此代码段假设<pre>
内第一行的缩进为0,并根据第一行重新排列所有行:
[].forEach.call(document.querySelectorAll('pre'), function($pre) {
var lines = $pre.textContent.split('\n');
var matches;
var indentation = (matches = /^\s+/.exec(lines[0])) != null ? matches[0] : null;
if (!!indentation) {
lines = lines.map(function(line) {
return line.replace(indentation, '');
});
return $pre.textContent = lines.join('\n').trim();
}
});
答案 4 :(得分:0)
当您使用pre
时,您应该将其内容格式化为您想要呈现的内容。这就是pre
(预先格式化的文本)的想法。但如果它只是缩进,您可以使用CSS:margin-left
具有合适的负值。