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


当前回答

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

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

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

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

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

其他回答

在Markdown v2.5.2中,你可以这样使用:

[link](URL){:target="_blank"}

如果有人正在寻找一个全局rmarkdown (pandoc)解决方案。

使用Pandoc Lua过滤器

你可以编写自己的Pandoc Lua过滤器,将target="_blank"添加到所有链接:

编写一个Pandoc Lua过滤器,例如links.lua

function Link(element)

    if 
        string.sub(element.target, 1, 1) ~= "#"
    then
        element.attributes.target = "_blank"
    end
    return element

end

然后更新你的_output.yml

bookdown::gitbook:
  pandoc_args:
    - --lua-filter=links.lua

在Header中注入<base target="_blank">

另一种解决方案是使用includes选项在HTML头部部分注入<base target="_blank">:

创建一个新的HTML文件,例如links.html

<base target="_blank">

然后更新你的_output.yml

bookdown::gitbook:
  includes:
    in_header: links.html

注意:此解决方案还可能为哈希(#)指针/ url打开新选项卡。我还没有用这样的url测试这个解决方案。

如果您只想在特定的链接中执行此操作,只需使用其他人回答的内联属性列表语法,或者只使用HTML。

如果你想在所有生成的<a>标签中这样做,这取决于你的Markdown编译器,也许你需要一个扩展。

这些天我正在为我的博客做这个,它是由pelican生成的,它使用Python-Markdown。我找到了Python-Markdown Phuker/markdown_link_attr_modifier的扩展,它工作得很好。注意,旧的名为newtab的扩展在Python-Markdown 3.x中似乎不起作用。

我不认为有降价功能,尽管如果你想用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。

完成alex回答(12月13日至10日)

一个更聪明的注入目标可以用下面的代码完成:

/*
 * For all links in the current page...
 */
$(document.links).filter(function() {
    /*
     * ...keep them without `target` already setted...
     */
    return !this.target;
}).filter(function() {
    /*
     * ...and keep them are not on current domain...
     */
    return this.hostname !== window.location.hostname ||
        /*
         * ...or are not a web file (.pdf, .jpg, .png, .js, .mp4, etc.).
         */
        /\.(?!html?|php3?|aspx?)([a-z]{0,3}|[a-zt]{0,4})$/.test(this.pathname);
/*
 * For all link kept, add the `target="_blank"` attribute. 
 */
}).attr('target', '_blank');

您可以通过在(?!html?|php3?|aspx?)组构造中添加更多扩展来更改regexp异常(请在这里了解这个regexp: https://regex101.com/r/sE6gT9/3)。

对于没有jQuery的版本,检查下面的代码:

var links = document.links;
for (var i = 0; i < links.length; i++) {
    if (!links[i].target) {
        if (
            links[i].hostname !== window.location.hostname || 
            /\.(?!html?)([a-z]{0,3}|[a-zt]{0,4})$/.test(links[i].pathname)
        ) {
            links[i].target = '_blank';
        } 
    }
}