将可点击元素放置在可点击容器元素

时间:2016-02-16 03:18:38

标签: javascript jquery html css hyperlink

我试图通过在其周围包裹一个链接元素来使#header div可点击,但是当它已经在div中有另一个图像链接时我不能这样做。我该如何解决这个问题?

#header {
border: 1px solid red;
background-color: red;
}
img {
width: 50px;
height: 50px;
}
<a href = 'index.php'>
<div id = 'header'>

<a href = 'profile.php?username=$username'>
<img src = 'https://www.iscattered.com/uploads/1590Chocolate_chip_cookies.jpg'>
</a> 

</div>
</a>

现在,虽然图片链接工作正常,但#wrapper div无法点击。

1 个答案:

答案 0 :(得分:2)

#header {
    border: 1px solid red;
    background-color: red;
    position: relative;    /* establish nearest positioned ancestor for abs. positioning */
    height: 50px;
}

#header a:first-child { 
    display: block;
    height: 100%;
}

#header a:last-child {
    position: absolute;      /* image now independently clickable */
    top: 0;                  /* position image anywhere you want inside #header */
    left: 0;
}

img {
    width: 50px;
    height: 50px;
}
<div id='header'>
    <a href='index.php'></a>
    <a href='profile.php?username=$username'>
   	<img src='https://www.iscattered.com/uploads/1590Chocolate_chip_cookies.jpg'>
    </a>
</div>

注意:

  • 如果您将超链接包装在另一个超链接中,浏览器应该如何知道要执行哪个链接?

  • 相反,要使#header元素完全可点击,并绝对定位图像。

  • 现在可以单独点击图片并将其放置在#header元素内的任何位置。

相关问题