求助:为锚点内span标签添加‘在新标签页打开’功能(CSS/JQuery)
解决方案:外部链接分场景打开功能实现
需求说明
- 外部链接自动添加图标
- 点击链接文本:当前窗口打开链接
- 点击图标:新标签页打开链接
- 鼠标悬停图标时显示「open in new tab」提示
完整代码实现
HTML 代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <p> This is <a href="https://test.com">the link<span class="ext-icon"></span></a> and some test text afterwards. <p> This is <a href="#anchor">an anchor link<span class="ext-icon"></span></a> (won't get external style). <p> This is <a href="/internal">an internal link<span class="ext-icon"></span></a> (won't get external style). <p> This is <a href="https://google.com">a google link<span class="ext-icon"></span></a> (won't get external style). </p>
CSS 代码
.external .ext-icon { width: 16px; height: 16px; display: inline-block; vertical-align: bottom; background-image: url('https://i.ibb.co/vvyC5JS/new-tab-60.png'); margin-left: 2px; background-size: contain; cursor: pointer; /* 提示可点击 */ }
JavaScript 代码
// 标记外部链接 $('a:not([href^="https://google.com"]):not([href^="#"]):not([href^="/"])').addClass('external'); // 为外部链接的图标添加功能 $('.external .ext-icon') // 添加悬停提示 .attr('title', 'open in new tab') // 图标点击事件 .on('click', function(e) { // 阻止事件冒泡,避免触发a标签的默认跳转 e.stopPropagation(); // 获取父级a标签的链接地址 const linkUrl = $(this).parent('a').attr('href'); // 新标签页打开链接 window.open(linkUrl, '_blank'); });
关键代码说明
- 图标点击事件:通过
e.stopPropagation()阻止事件冒泡,确保点击图标时不会触发a标签的默认跳转行为 - 悬停提示:给图标添加
title属性,实现鼠标悬停时的提示文本 - 新标签打开:使用
window.open()方法,传入_blank参数在新标签页打开链接 - 选择器优化:将原有的
id="ext"改为类名.ext-icon,支持多个外部链接的场景
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

