[html] a标签可以再嵌套a标签吗?为什么?如果不行,那又想要嵌套效果怎么解决呢?
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>
个人简介
我是歌谣,欢迎和大家一起交流前后端知识。放弃很容易,
但坚持一定很酷。欢迎大家一起讨论
主目录
与歌谣一起通关前端面试题