How to preserve whitespace indentation of text enclosed in HTML
 tags excluding the current indentation level of the 
 tag in the document?

后端 未结 11 1464
萌比男神i
萌比男神i 2020-12-02 18:32

I\'m trying to display my code on a website but I\'m having problems preserving the whitespace indentation correctly.

For instance given the following snippet:

11条回答
  •  眼角桃花
    2020-12-02 18:38

    This can be done in four lines of JavaScript:

    var pre= document.querySelector('pre');
    
    //insert a span in front of the first letter.  (the span will automatically close.)
    pre.innerHTML= pre.textContent.replace(/(\w)/, '$1');
    
    //get the new span's left offset:
    var left= pre.querySelector('span').getClientRects()[0].left;
    
    //move the code to the left, taking into account the body's margin:
    pre.style.marginLeft= (-left + pre.getClientRects()[0].left)+'px';
     
       Here is my code:
       
         def some_funtion
           return 'Hello, World!'
         end
       

提交回复
热议问题