在插件开发中,扩展数据注入位置完全得根据宿主网站的设计适配,其中最无奈的就是得注入到A标签里去,但根据W3C的html解析协议,A标签是内联元素(inline element)不能嵌套A标签的,如果发生嵌套则会被拆分,这样就会导致我们扩展数据无法使用A标签了,也会影响我们扩展数据的点击事件
<!-- a标签进行嵌套的时候 -->
<a href="#outer">outerA
<a href="#inner">innerA</a>
</a>
<!-- 而浏览器则会解析成 -->
<a href="#outer">outerA</a>
<a href="#inner">innerA</a>
解决方法1(绝对定位)
将外层a标签改为行内块级元素即display:inline-block;设置height/width并设置为绝对定位将其放在里层a标签的位置,通过调整里层a标签及外层a的z-index大小,使得鼠标能正确选中a标签;
解决方法2 (object标签)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript" src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<div>
<a href="http://www.baidu.com" target="_blank">
<div style="width: 300px;height: 150px; background-color: blue;">容器1</div>
<div style="width: 300px;height: 150px; background-color: red;">容器2</div>
<object style="display: block;width: 300px;height: 150px; background-color: skyblue;" class="zsl-wrap zslj-wrap">
容器3
<a href="https://www.qq.com" target="_blank">腾讯</a>
</object>
</a>
</div>
<script type="text/javascript">
// 容器底下的所有A对象不进行冒泡
$(document).on('click', '.zslj-wrap a', function(event) {
event.stopPropagation();// 阻止冒泡
console.log('阻止了冒泡,保留A默认事件');
})
$(document).on('click', '.zslj-wrap', function(event){
event.preventDefault();// 阻止超链接
console.log('阻止了超链接');
});
</script>
</body>
</html>