【问题标题】:How can you make a div clickable by a link in the div without changing HTML如何在不更改 HTML 的情况下通过 div 中的链接使 div 可点击
【发布时间】:2021-08-10 02:55:12
【问题描述】:

我正在尝试制作一个包含文本和链接的 div,但该 div 应该是可点击的。

我知道我能做到:

<a href="#link">
  <div>
    <p> some text</p>
    <a href="#" class="btn_link">my link</a>
  </div>
</a>

但就我而言,我需要在 div 中放置一个链接,当我单击 div 时,我应该被重定向到带有此类“btn_link”的a标签中的链接,以及a标签应该不可见

我已经尝试过这样做:

<div class="my_div">
  <p> some text</p>
  <a href="#link" class="btn_link"></a>
</div>

CSS:

.btn_link a {
  background: none !important;
  border: none !important;
}

我不知道如何让按钮覆盖整个 div 以使其可点击。

注意:我无法更改 HTML 结构,使用 CSS 很重要。

谁能告诉我可以使用什么 CSS 属性来实现这一点?

【问题讨论】:

  • 你会用javascript吗?

标签: html css flexbox css-selectors


【解决方案1】:

绝对定位链接

.btn_link {
  position: absolute;
  inset: 0;
  background: rgba(0, 0, 0, .15);
}

.my_div {
  position: relative;
}
<div class="my_div">
  <p> some text</p>
  <a href="#link" class="btn_link"></a>
</div>

【讨论】:

    【解决方案2】:

    您可以使用一些额外的 Javascript 代码来做到这一点。

    // set an event listener to the div
    document
      .querySelector(".link_div")
      .addEventListener("click", function() {
        // calculate the position of the element immediately
        // after .btn_link. We cannot get the offsetTop for .btn_link because it is hidden (display:none) so the Y position of immediate next element should be as good as itself.
        posY = document.querySelector(".btn_link").nextElementSibling.offsetTop
        window.scrollTo(0, posY)
      });
    .btn_link {
      display: none
    }
    
    .spacer {
      padding-bottom: 120vh;
      background: #ececec;
    }
    <div class="link_div">
      <p>some text</p>
      <p class="spacer">some space to show how scroll is working .... </p>
      <a href="#link" class="btn_link"></a>
      <p>some text after the link. The link above is hidden</p>
    </div>

    【讨论】:

      【解决方案3】:

      这里只有 HTML 和 CSS:

      HTML

      <!DOCTYPE html>
      <html>
      <head>
      <link href="test.css" rel="stylesheet" type="text/css">
      </head>
      <body>
          
      <!--The <div>, like you wanted-->
      <div>
      <!--This  will be the link in the background-->
      <a class="hidden-link" href="example.com">
      <!--Your text (Wich is a hidden link)-->
      <p>Some Text</p>
      <!--Your official link-->
      <a href="example.com">My Link</a>   
      </a>
      </div>
          
      </body>
      </html>
      

      CSS

      .hidden-link{
          text-decoration-line: none;
          color: black;
      }
      

      输出:

      Output-Click me to see the image

      两个链接都指向“example.com”,除了一个隐藏为文本,另一个显然是一个链接。

      【讨论】:

      • OP 无法更改 HTML
      猜你喜欢
      • 1970-01-01
      • 2014-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-01
      • 2015-09-24
      相关资源
      最近更新 更多