[英]Wrapping DIV inside Anchor tag or otherwise
Suppose I have a clickable complex div
element structure which links to another page as follows. 假设我有一个可点击的复杂
div
元素结构,它链接到另一个页面,如下所示。 This is the thing that is being achieved currently on click. 这是目前正在点击的事情。 On click (css :active state) change the background color inside
<a>
tag and redirect to other page. 单击(css:活动状态)更改
<a>
标签内的背景颜色并重定向到其他页面。
I am wondering whether this conforms to HTML5 validation or consider as a best practice compared to wrapping it with a div
and using JavaScript to manage the link redirect and background color change on click. 我想知道这是否符合HTML5验证或者考虑作为最佳实践,与使用
div
包装并使用JavaScript管理链接重定向和点击背景颜色更改相比。
To me, the first approach seems to be much cleaner and straight forward. 对我而言,第一种方法似乎更清洁,更直接。
I believe this is a common issue face by a lot of web developers but I am not sure whether there is an existing best practice solution for this. 我相信这是许多Web开发人员面临的常见问题,但我不确定是否存在现有的最佳实践解决方案。
1) Maintain as this 1)保持这一点
<a href="page1.html">
<div>
<!-- complex layout -->
</div>
</a>
2) Omit the <a>
tag and manage background color during click event and redirect using JavaScript 2)在点击事件期间省略
<a>
标签并管理背景颜色,并使用JavaScript重定向
<div id="#redirectLink" data-link="page1.html">
<!-- complex layout -->
</div>
HTML5 , you can wrap a DIV
inside an A
anchor HTML5 ,您可以将
DIV
包装在A
锚点中
<a href="page1.html">
<div>
<!-- complex layout -- BUT WITHOUT ANCHORS -->
</div>
</a>
only if inside <!-- complex layout -->
you don't have another <a>
只有在
<!-- complex layout -->
你没有另外的<a>
Otherwise you can do: 否则你可以这样做:
<div id="#redirectLink" data-link="page1.html">
<!-- complex layout -->
</div>
<script>
[].forEach.call(document.querySelectorAll("[data-link]"), function(el) {
el.addEventListener("click", function(){
window.location.href = el.dataset.link;
}, false);
});
</script>
or simply: 或者干脆:
<div id="#redirectLink" onclick="window.location.href='page1.html';">
<!-- complex layout -->
</div>
Your first approach conforms to HTML5. 您的第一种方法符合HTML5。 a-tags can have children, just not more links.
a-tags可以有孩子,只是没有更多的链接。
Is it legal to have children of an anchor tag (<a>) in HTML? 在HTML中拥有锚标记(<a>)的子项是否合法?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.