最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - highlight.js inline mode possible? - Stack Overflow

programmeradmin1浏览0评论

I was able to make a code-block with highlight.js like this:

<pre>
  <code class="haskell">
    {-# OPTIONS_GHC -Wall #-}
    euclid :: Int -> Int -> Int
    euclid a b
      | a == 0    = b
      | b == 0    = a
      | a > b     = euclid (a-b) b
      | otherwise = euclid a (b-a)
  </code>
</pre>

Works fine! But now I also want to have some code lines in my text, inline. Like this:

<p> Info text inline code testing <code class="haskell">{-# OPTIONS_GHC -Wall #-}</code> maybe it works</p>

Doesn't work... You can check them out at my Site

How to make inline code with highlight.js ?

I was able to make a code-block with highlight.js like this:

<pre>
  <code class="haskell">
    {-# OPTIONS_GHC -Wall #-}
    euclid :: Int -> Int -> Int
    euclid a b
      | a == 0    = b
      | b == 0    = a
      | a > b     = euclid (a-b) b
      | otherwise = euclid a (b-a)
  </code>
</pre>

Works fine! But now I also want to have some code lines in my text, inline. Like this:

<p> Info text inline code testing <code class="haskell">{-# OPTIONS_GHC -Wall #-}</code> maybe it works</p>

Doesn't work... You can check them out at my Site

How to make inline code with highlight.js ?

Share Improve this question asked Sep 27, 2015 at 21:17 Martin FischerMartin Fischer 6971 gold badge7 silver badges28 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 14 +50

You just need a little CSS to make it inline. How you do it is up to you, but you could make it inline if it's within a p tag.

p > code.hljs { display: inline; }

Example: https://jsfiddle/ykyLcvnw/1/

In your first example, you use both a <pre> and a <code> tag. This isn't the case in your second.

From the highlight.js usage page:

This will find and highlight code inside of <pre><code> tags;

I've additionally sourced this example from the usage page:

 $('pre code').each(function(i, block) {
   hljs.highlightBlock(block);
 });

Since your inline markup is in a <span> tag, that is, the hierarchy is span code, you can achieve inline highlighting with something like:

 $('span code').each(function(i, inline) {
   hljs.highlightBlock(inline);
 });

I ran this code in the console on your test page, and I'm seeing the results. Assuming you're not using jQuery, the pseudo code is just

  1. iterate over all desired elements
  2. apply hljs.highlightBlock(element)

It'll be much simpler if you define your own inline class in CSS like this

.inline{
    display: inline;
}

Then set your code tag's class attribute to haskell inline.
That's it, you can make it the same way for any other language by replacing haskell with your language of choice.

发布评论

评论列表(0)

  1. 暂无评论