Google Code Prettify 实现代码高亮

11 篇文章 0 订阅

Google Code Prettify 实现代码高亮

Posted 2012-11-13  | 分类:  JavaScript    

Prettify提供一个Javascript模块和CSS 文件,可以在HTML页面中显示源代码的代码高亮效果。这是用于code.google.com的脚本。

语法

<pre class="prettyprint" id="language">
@*你的代码片断*@
</pre>

常用的语言

将id的language改成以下的语言:

bash”, c”, cc”, cpp”, cs”, csh”, cyc”, cv”, htm”, html”, java”, js”, m”, mxml”, perl”, pl”, pm”, py”, rb”, sh”, xhtml”, xml”, xsl

prettify.js 的使用方法:

1、引入 jQuery 文件和 prettify.js 文件
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script src="prettify.js" type="text/javascript"></script>
2、调用 prettify.js 实现代码高亮

在 body 标签上添加调用方法,如下:

<body onload="prettyPrint()">
</body>

将你需要高亮显示的代码片断放在<pre>标记里,如下:

<pre class="prettyprint">
@*你的代码片断*@
</pre>

使用 jQuery 小技巧实现优化

上述方法可以实现代码的高亮,但每次手动为<pre>标签添加"prettyprint"类,显示有些麻烦。使用下边的代码片断来解决这个问题并替换掉 body 的"onload"的事件,实现分离:

<script type="text/javascript">
$(window).load(function(){
    $("pre").addClass("prettyprint");
    prettyPrint();
})
</script>

到这我们应该已经成功使用 prettify.js 实现了代码的高亮显示,为了提高页面加载速度,我们应该将引用的 js 文件放置在底部,大家可以参考下本站的放置方法。

DEMO JAVA代码高亮显示


   
   
  1. package foo;
  2.  
  3. import java.util.Iterator;
  4.  
  5. /**
  6. * the fibonacci series implemented as an Iterable.
  7. */
  8. public final class Fibonacci implements Iterable<Integer> {
  9. /** the next and previous members of the series. */
  10. private int a = 1, b = 1;
  11.  
  12. @Override
  13. public Iterator<Integer> iterator() {
  14. return new Iterator<Integer>() {
  15. /** the series is infinite. */
  16. public boolean hasNext() { return true; }
  17. public Integer next() {
  18. int tmp = a;
  19. a += b;
  20. b = tmp;
  21. return a;
  22. }
  23. public void remove() { throw new UnsupportedOperationException(); }
  24. };
  25. }
  26.  
  27. /**
  28. * the n<sup>th</sup> element of the given series.
  29. * @throws NoSuchElementException if there are less than n elements in the
  30. * given Iterable's {@link Iterable#iterator iterator}.
  31. */
  32. public static <T>
  33. T nth(int n, Iterable<T> iterable) {
  34. Iterator<? extends T> it = iterable.iterator();
  35. while (--n > 0) {
  36. it.next();
  37. }
  38. return it.next();
  39. }
  40.  
  41. public static void main(String[] args) {
  42. System.out.print(nth(10, new Fibonacci()));
  43. }
  44. }
个人博客:http://demi-panda.com
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值