Cha*_*kjh 8 html javascript jquery
我这里有一点问题.我有一个div带h1, h2 and p.我想把div变成一个链接,但我不能只<a>围绕一个div或h1,h2,p.这不是正确的方法,但我该怎么做才能将整个div变为链接?我应该把每个元素都变成一个span吗?这将需要更多的工作
<a href="#" class="link">
<span class="div">
<span class="h1"></span>
<span class="h2"></span>
<span class="p"></span>
</span>
</a>
Run Code Online (Sandbox Code Playgroud)
或者我应该使用javascript:
$('.link').click(function(){
document.location.href='#';
})
Run Code Online (Sandbox Code Playgroud)
您不需要任何JS或jQuery来执行此操作.另一种方法是做这样的事情:
<div>
<a href="#"></a>
<h1>Something</h1>
<h2>Something else</h2>
<p>Another something</p>
</div>
<style type="text/css">
div {
position: relative;
}
div > a {
display: block;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 2;
}
</style>
Run Code Online (Sandbox Code Playgroud)
当然,更改CSS选择器,以便它们只影响您希望它们影响的任何内容.当然,如果用户没有启用JS,它仍然可以完全正常工作,并且它对SEO更好.
假设您的原始HTML看起来如下所示,您应该添加一个data参数,其中包含单击div时要遵循的链接:
<div class="link" data-url="http://www.google.com">
<span class="div">
<span class="h1"></span>
<span class="h2"></span>
<span class="p"></span>
</span>
</div>
Run Code Online (Sandbox Code Playgroud)
然后你可以附加一个click处理程序div:
$('.link').click(function() {
window.location.assign($(this).data('url'));
});
Run Code Online (Sandbox Code Playgroud)
最后,确保cursor在CSS中添加属性,这样很明显div是可点击的:
.link { cursor: pointer; }
Run Code Online (Sandbox Code Playgroud)