Typecho自动在新窗口中打开链接

·
Typecho no tag October 13, 2018
!本文可能 超过2年没有更新,今后内容也许不会被维护或者支持,部分内容可能具有时效性,涉及技术细节或者软件使用方面,本文不保证相应的技术更新和实践可操作性。

js查找网页中的外部链接

$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])")

这段代码能够找到包含http和https的所有外部链接 (a) 标签。如果你想找到所有的 (a) 标签,改成$("a")就可以了。
添加新窗口属性

$("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])").addClass("external").attr("target","_blank");
  • addClass("external")是给所有的外部链接添加class="external",这样可以在css里面控制它的样式;
  • attr("target","_blank")是添加新窗口打开的属性。

将js代码添加进主题的footer.php

<script src="<?php $this->options->themeUrl('js/jquery.min.js'); ?>"></script>
<!-- 这段代码在 jquery-min.js 加载之后添加 -->
<script type="text/javascript">
    $("a[href*='http://']:not([href*='"+location.hostname+"']),[href*='https://']:not([href*='"+location.hostname+"'])").addClass("external").attr("target","_blank");
</script>

注:主题中本来就已经加入了js/jquery-2.1.4.min.js,所以只要放在这一条的后面就可以了。


首次创建时间:2018-10-13 00:41:00
最后修改时间:2018-10-13 01:02:19

  • 小时了了 大未必佳
  • Moricolor主题去掉分享按钮保留功能按钮

_(:3 」∠)_
(抱歉)
自发布之日起超123天后自动关闭评论哦!


© 2025 Mr.Cui's Blog. Using Typecho & Moricolor.

鲁ICP备16004095号-2
鲁公网安备37028502250699号
HTTP/3 IPv6