日期:2014-05-16  浏览次数:20978 次

[HTML/CSS应用]博客文档排版之源码编辑模式下在文章中插入代码

上一篇博客我们介绍了如何设置比较合适的行间距与段间距,这篇文章我们将介绍如何在源码编辑模式下,向文章中插入代码。我们将介绍两种方式。

第一种插入代码的方式:

自定义代码样式;我们看下面的示例,这里我们演示在文章中插入一段html代码

<div style="border: 2px solid blue; background-color:#CCC; padding:10px 20px;line-height:1.5;">
    <pre style="overflow:auto">
        &lt;div style="line-height:1.5;text-indent:30px;font-size:1.2em;font-family:'楷体';"&gt;
        &lt;h2 style="text-align:center;margin:20px;"&gt;幸福是心的感觉&lt;/h2&gt;
        &lt;p style="margin:0px 0px 10px 0px;"&gt;生活中不缺美......&lt;/p&gt;
        &lt;p style="margin:0px 0px 10px 0px;"&gt;生活中不缺幸福......&lt;/p&gt;
        &lt;/div&gt;
    </pre>
</div>

注解:上述示例定义了一个蓝色边框、灰色背景的代码块显示区;<pre>与</pre>之间是代码块

border            边框

background-color  背景色

padding           内边距

line-height       行高

需要注意的是:“<”与“>”是HTML保留字符。我们在插入代码时需要进行相应替换,使用“&lt;”代替“<”,使用“&gt;”代替“>”。

上述示例实际显示效果如下:

<div style="line-height:1.5;text-indent:30px;font-size:1.2em;font-family:'楷体';">
<h2 style="text-align:center;margin:20px;">幸福是心的感觉</h2>
<p style="margin:0px 0px 10px 0px;">生活中不缺美......</p>
<p style="margin:0px 0px 10px 0px;">生活中不缺幸福......</p>
</div>

第二种插入代码的方式:

使用CSDN定义的样式;我们看下面的示例,这里我们演示在文章中插入一段cpp代码

<pre name="code" class="cpp">
    #include &lt;QApplication&gt;
    #include &lt;QLabel&gt;
    
    int main(int argc, char *argv[])
    {
        QApplication app(argc, argv);
        QLabel *label = new QLabel(&quot;Hello Qt!&quot;);
        label-&gt;show();
        return app.exec();
    }
</pre>

注解:上述示例中我们没有自定义边框,而是使用CSDN的样式;<pre>与</pre>之间是代码块

同样,我们需要使用“&lt;”代替“<”,使用“&gt;”代替“>”。

<pre>中class为代码类型,目前CSDN提供的可选类型有

"html"、"objc"、"javascript"、"css"、"php"、"csharp"、"cpp"、"java"、"python"、"ruby"、"vb"、"delphi"、"sql"、"plain&quo