在Markdown中,有没有办法阻止图像被<p>标签包裹?</p>

时间:2014-06-27 15:54:12

标签: html image markdown jekyll

我使用的是Jekyll,所有帖子都是.md格式以方便使用。 问题是生成器会自动包装段落标记中的每一行。

line

<img>

line

变为

<p>line</p>

<p><img></p>

<p>line</p>

这意味着我的图片被限制为我为段落设置的宽度,这会弄乱我的风格。

我可以做些什么来避免这种情况?我已经尝试了图像的html语法和markdown语法,但似乎没有任何效果。

谢谢!

4 个答案:

答案 0 :(得分:9)

我不这么认为。原Markdown spec says

  

段落只是一行或多行文本,由一个或多个空行分隔。

虽然可能会提出一些漂亮的CSS来修复你的样式问题。

或者你可以试试这个黑客(在Pandoc中工作):

line

<div><img></div>

line

答案 1 :(得分:8)

图像是内联元素,旨在驻留在像段落一样的块级元素中。因此,Markdown解析器会纠正您的“错误”并将img包装在段落标记内。

将img标记包装到适当的块级元素中,如图所示,可以防止出现这种情况。例如:

<figure><img src=""></figure>

如果您希望自动化一些,您不打算在Github页面上生成您的网站(不允许使用插件),那么您可以使用插件来帮助实现这一目标。使您的帖子中的图像插入更容易。我正在使用此插件的修改版本:

https://github.com/opattison/jekyll-figure-image-tag/blob/master/figure_image_tag.rb

答案 2 :(得分:0)

正如其他人所说,图像是内联元素,Markdown解析器会强制它们被包含在块级元素中。目前接受的答案是hacky:它在你的降价中看起来很乱,不稳健/可扩展,并且不易修改。我将Middleman用于我的博客,并为我的图像创建了一个部分图像,可以完成我想要图像处理的所有内容。我假设/希望Jekyll也有部分内容,而且这个答案,虽然在语法上与Jekyll不同,但仍然与你相关。

请注意,如果他们不以&#34; http://&#34;,&#34; https:/&#34;或&#34; /&#34;。这是因为我的博客图像具有可靠的组织结构,并且在使用此部分时更简单,我只需要图像名称而不需要其路径的其他部分。

这是部分:

partials/_image.erb

<%
#initialize local variables in case they were not included
caption ||= ""
alt ||= ""
classes ||= ""

#strip '.html' extension off article link to get name of folder
url = current_article.url
url_without_ext = url[0..url.length-6]

#determine if image has an exact link or belongs to "/images/blog/CURRENT_ARTICLE_NAME/"
prefix = src[0..6]
if prefix != "http://" and prefix != "https:/" and src[0] !="/" then
  #image belongs to "/images/blog/CURRENT_ARTICLE_NAME/" - add prefix to src
  src = "/images#{url_without_ext}/#{src}"
end
%>

<!-- Use Kramdown's 'nomarkdown' tag so that this figure is not wrapped in a 'p' tag in the blog pages that use this partial -->
{::nomarkdown}
<figure class="<%= classes %>">
  <!-- Show the image and link to the full resolution on click-->
  <a target="_blank" href="<%= src %>" >
    <img src="<%= src %>" alt="<%= alt %>">
  </a>

  <figcaption><%= caption %></figcaption>
</figure>
{:/}

并将此部分称为

不会添加任何前缀:

<%= partial "partials/image.erb", locals: {
    src: "/images/icons/tech/atom.svg",
    alt: "Atom",
    classes: "icon" } %>

将添加前缀:

<%= partial "partials/image.erb", locals: {
    src: "my-lovely-dog.svg",
    alt: "Dog",
    caption: "Woof woof!",
    classes: "icon" } %>

我保持这部分最新here(如果我添加/编辑其中任何一个)。

答案 3 :(得分:0)

这里有一些 javascript 可以为您解开它们:

const allPTags = document.querySelectorAll("p");

allPTags.forEach((elem) => {
    if (elem.innerText === "" && elem.childNodes.length === 1 && elem.childNodes[0].tagName === "IMG") {
        elem.parentNode.insertBefore(elem.childNodes[0], elem);
        elem.remove();
    }
});
相关问题