有没有办法在Markdown中创建一个在新窗口中打开的链接?如果不是,您建议使用什么语法来完成此操作?我将把它添加到我使用的markdown编译器中。我认为这应该是一个选择。


当前回答

没有简单的方法来做到这一点,就像@alex指出的那样,你需要使用JavaScript。他的答案是最好的解决方案,但为了优化它,你可能只想过滤到内容后链接。

<script>
    var links = document.querySelectorAll( '.post-content a' );  
    for (var i = 0, length = links.length; i < length; i++) {  
        if (links[i].hostname != window.location.hostname) {
            links[i].target = '_blank';
        }
    }
</script>

该代码与IE8+兼容,您可以将其添加到页面底部。注意,您需要更改“。Post-content (Post-content)指向你在帖子中使用的类。

如下所示:http://blog.hubii.com/target-_blank-for-links-on-ghost/

其他回答

React + Markdown环境:

我创建了一个可重用组件:

export type TargetBlankLinkProps = {
  label?: string;
  href?: string;
};

export const TargetBlankLink = ({
  label = "",
  href = "",
}: TargetBlankLinkProps) => (
  <a href={href} target="__blank">
    {label}
  </a>
);

我在任何需要在新窗口中打开链接的地方都使用它。

仅对外部链接自动,使用GNU sed & make

如果有人想系统地为所有外部链接做这件事,CSS是没有选择的。然而,一旦Markdown创建了(X)HTML,就可以运行下面的sed命令:

sed -i 's|href="http|target="_blank" href="http|g' index.html

通过将上述sed命令添加到makefile中,可以进一步实现自动化。有关详细信息,请参阅GNU make或在我的网站上查看我是如何做的。

我不认为有降价功能,尽管如果你想用JavaScript自动打开指向你自己网站以外的链接,可能有其他可用的选项。

Array.from(javascript.links)
    .filter(link => link.hostname != window.location.hostname)
    .forEach(link => link.target = '_blank');

jsFiddle。

如果你正在使用jQuery:

$(document.links).filter(function() {
    return this.hostname != window.location.hostname;
}).attr('target', '_blank');

jsFiddle。

我正在使用Grav CMS,这是完美的:

阀体/内容: 一些文本[1]

车身/参考: [1]: http://somelink.com/?target=_blank

只要确保目标属性首先被传递,如果链接中有其他属性,将它们复制/粘贴到引用URL的末尾。

也可以作为直接链接: [进入本页](http://somelink.com/?target=_blank)

使用MUI v5“markdown-to-jsx”

这似乎对我很管用:

import Markdown from 'markdown-to-jsx';

...

  const MarkdownLink = ({ children, ...props }) => (
    <Link {...props}>{children}</Link>
  );

...

          <Markdown
            options={{
              forceBlock: true,
              overrides: {
                a: {
                  component: MarkdownLink,
                  props: {
                    target: '_blank',
                  },
                },
              },
            }}
          >
            {description}
          </Markdown>