I have the following HTML:
<body>
Here is some code:
<pre><code>
Here is some fun code!
</code></pre>
</body>
But when I preview it, because the code is indented, the pre is all out of whack. I can fix that by bringing the contents back against the indent, but it looks silly. Can I make that above text look non-indented?
答案 0 :(得分:5)
答案 1 :(得分:4)
Here you go, I decided to come up with something more concrete than changing the way pre
or code
work. So I made some regex to get the first newline character \n
(preceded with possible whitespace - the \s*
is used to cleanup extra whitespace at the end of a line of code and before the newline character (which I noticed yours had)) and find the tab or whitespace characters following it [\t\s]*
(which means tab character, whitespace character (0 or more) and set that value to a variable. That variable is then used in the regex replace function to find all instances of it and replace it with \n
(newline). Since the second line (where pattern
gets set) doesn't have the global flag (a g
after the regex), it will find the first instance of the \n
newline character and set the pattern
variable to that value. So in the case of a newline, followed by 2 tab characters, the value of pattern
will technically be \n\t\t
, which will be replaced where every \n
character is found in that pre code
element (since it's running through the each function) and replaced with \n
$("pre code").each(function(){
var html = $(this).html();
var pattern = html.match(/\s*\n[\t\s]*/);
$(this).html(html.replace(new RegExp(pattern, "g"),'\n'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
Here is some code:
<pre><code>
Here is some fun code!
More code
One tab
One more tab
Two tabs and an extra newline character precede me
</code></pre>
</body>
答案 2 :(得分:1)
This works, assuming indentation should be based on the first line of code:
//get the code element:
var code= document.querySelector('pre code');
//insert a span in front of the first letter. (the span will automatically close.)
code.innerHTML= code.textContent.replace(/(\w)/, '<span>$1');
//get the new span's left offset:
var left= code.querySelector('span').getClientRects()[0].left;
//move the code to the left, taking into account the body's margin:
code.style.marginLeft= (-left + code.getClientRects()[0].left)+'px';
code {
display: block; //this is necessary for the JavaScript to work properly
}
<body>
Here is some code:
<pre><code>
Here is some fun code!
And some more!
Continuing
Wrapping up
Closing code now.
</code></pre>
</body>