一直以来都觉得在图片下面添加一个标题可以更加清晰的表示这张图片的含义, 可是博客园原生并不支持这种渲染方式, 再加上博客园可以自己写 js 来更改主题, 于是通过搜索资料完成给博客园图片添加标题的功能.
当我们如下书写 markdown 时:
![](https://images.morethink.cn/092017231747399.jpg "TCP 的三次握手和四次挥手")
会被博客园渲染成
<p><img src="https://images.morethink.cn/092017231747399.jpg" title="TCP 的三次握手和四次挥手"></p>
于是我就想通过在 img 标签后面动态添加一个带有 title 的 p 标签来给博客园图片添加标题.
将下面代码放入页首 html 代码代码中即可 (需要申请 js 权限).
<!-- 引入 jQuery -->
- <script src="http://cdn.bootCSS.com/jquery/1.10.2/jquery.min.js"></script>
- <script type="text/javascript">
- $(window).load(function () {
- // 给每张图片添加标题, div.cnblogs_post_body 是博客主体
- $("div[id=cnblogs_post_body] img").each(function () {
- var title = $(this).attr("title");
- var boardp_style = "style='display: block; text-align: center; color: #969696;padding: 10px;border-bottom: 1px solid #d9d9d9;margin: 0 auto;"+"width: "+ ($(this).width() * 0.8) +"px;"+"height: 28px;"+"'>";
- var boardp = "<p" + boardp_style + title + "</p";
- $(this).after(boardp);
- });
- });
- </script>
- <!-- 将 img 变为块级元素 -->
- <style type="text/css">
- img {
- margin: 0 auto;
- display: block;
- }
- </style>
markdown 图片:
![](https://images.morethink.cn/092017231747399.jpg "TCP 的三次握手和四次挥手")
来源: https://www.cnblogs.com/morethink/p/8998015.html