2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

HTML ファイル内に直接書いた Markdown を変換して GitHub のスタイルで表示させる話

Posted at

概要

marked.js を用いて,HTML ファイル内に直接記述された Markdown を変換し,さらに github-markdown-css を用いて GitHub の Markdown スタイルで表示させる.

詳細

かつてこんなことを呟いていた:

上記ツイートにもある通り,こちらの記事を参考にして,HTML ファイル内に直接記述された Markdown を変換・表示させた.以下はそのサンプルコードである:

markdown.html
<!DOCTYPE html>
<title>Markdown</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<div id="mdrender"></div>
<div id="mdraw" style="display:none;">
# 見出し1
## 見出し2
### 見出し3
#### 見出し4
##### 見出し5
###### 見出し6
*italic*
**太字**
**bold and _italic_**
~~取り消し線~~
[リンク (GitHub)](https://github.com/)
1. 富士
2. 鷹
3. 茄子
- 箇条書き1
    - 箇条書き2
        - 箇条書き3

> 吾輩は猫である。
> 名前はまだ無い。
</div>
<script>
  document.getElementById("mdrender").innerHTML = marked(document.getElementById("mdraw").innerHTML.replace(/&gt;+/g, '>'));
</script>

実際の表示は次のようになる:
markdown
これで呟きは実現されたわけだが,ちょっとページが味気ない.何か適当なスタイルシートを適用できれば良いなと思い探してみたら github-markdown-css というのを見つけた.このスタイルシートを適用すると,GitHub 上で Markdown 形式の文書を閲覧したときと同様の表示にできる.以下はそのサンプルで,先ほどのサンプルコードに一部追記したものである:

github-markdown.html
<!DOCTYPE html>
<title>GitHub Markdown CSS</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0">
<link rel="stylesheet" href="https://sindresorhus.com/github-markdown-css/github-markdown.css">
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<div id="mdrender" class="markdown-body"></div>
<div id="mdraw" style="display:none;">
# 見出し1
## 見出し2
### 見出し3
#### 見出し4
##### 見出し5
###### 見出し6
*italic*
**太字**
**bold and _italic_**
~~取り消し線~~
[リンク (GitHub)](https://github.com/)
1. 富士
2. 鷹
3. 茄子
- 箇条書き1
    - 箇条書き2
        - 箇条書き3

> 吾輩は猫である。
> 名前はまだ無い。
</div>
<script>
  document.getElementById("mdrender").innerHTML = marked(document.getElementById("mdraw").innerHTML.replace(/&gt;+/g, '>'));
</script>

具体的な追加内容は次の通り:

  • 適用するスタイルシートを表記:
<link rel="stylesheet" href="https://sindresorhus.com/github-markdown-css/github-markdown.css">
  • スタイルシートが適用されるクラス markdown-body を表記:
<div id="mdrender" class="markdown-body"></div>

実際の表示は次のようになる:
github-markdown
GitHub を使う人にはお馴染みの見た目である.

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?