a标签不能嵌套a标签
<a href="https://www.baidu.com/" class="parent">
点击父级标签
<a href="https://www.baidu.com/" target="_blank" class="child">点击子级标签</a>
</a>
结果在浏览器上解析为,嵌套失败:
<a href="https://www.baidu.com/" class="parent">点击父级标签</a>
<a href="https://www.baidu.com/" target="_blank" class="child">点击子级标签</a>
那么实现嵌套效果(点击子标签时跳转,点击父标签时跳转):
1.和上面的布局一样,样式改变如下,给父元素加绝对定位:
.parent {
display: block;
position: absolute;
width: 200px;
height: 100px;
border: 1px solid blue;
text-align: center;
line-height: 100px;
}
.child {
color: red;
}
2.中间加一层object标签如下(大部分浏览器支持,但是还是存在兼容性):
<a href="https://www.baidu.com/" class="parent">
点击父级标签
<object data="" type="">
<a href="https://www.baidu.com/" target="_blank" class="child">点击子级标签</a>
</object>
</a>
3.还可以不用a标签(随便用什么标签,实现嵌套和跳转功能),加js如下:
<div class="parent" id="parent">
点击父级标签
<a href="https://www.baidu.com/" target="_blank" rel="noopener noreferrer" class="child" id="child">点击子级标签</a>
</div>
<script>
window.onload = () => {
let parent = document.getElementById('parent');
let child = document.getElementById('child');
parent.onclick = () => {
alert("在本页跳转到百度");
window.location.href = 'https://www.baidu.com/';
};
child.onclick = (e) => {
// 阻止事件默认的向上冒泡行为
e.stopPropagation();
alert("打开新页面跳转到百度");
};
};
</script>