9

我这里有个小问题。我有一个divwith h1, h2 and p。我想将 div 变成一个链接,但我不能只将 a 包裹<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>

或者我应该使用javascript:

$('.link').click(function(){
   document.location.href='#';
})
4

4 回答 4

9

You don't need any JS or jQuery to do this. An alternative would be to do something like this:

<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>

Of course, change the CSS selectors so that they only affect whatever you want them to affect. The advantages of this are of course if the user doesn't have JS enabled, it will still completely work normally, and it's better for SEO.

于 2013-01-28T10:58:40.367 回答
6

假设您的原始 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>

然后您可以将click处理程序附加到div

$('.link').click(function() {
    window.location.assign($(this).data('url'));
});

最后,确保cursor在 CSS 中添加属性,这样 div 是可点击的:

.link { cursor: pointer; }
于 2013-01-28T10:41:47.500 回答
2
<div onclick="window.location = 'http://www.abc.com/';" style="cursor:pointer;">

</div>
于 2013-01-28T10:48:36.800 回答
1

To elaborate on what Rory has proposed I think it might be safter to incude an actual link inside your div incase the user does not have javascript enabled and for search engine indexing.

<div class="link">
  <h1><a href="http://www.google.com">Heading One</a></h1>
  <h2>Heading Two</h2>
  <p>Paragraph</p>
</div>

Then search for the h1 link and use that as the url

$('.link').on('click', function() {
    window.location = $(this).find('h1 a').attr('href');
});

And the CSS

.link { cursor:pointer; }   
于 2013-01-28T11:00:07.313 回答