首页 > 解决方案 > 如何有一个可点击的按钮

问题描述

我有一个文本链接作为“点击我到达那里”,我通过 CSS 将其转换为一个按钮。

这是我成功使用的:

.product-buttons-container {
  background-color: #ff6347;
  padding: 11px 24px;
  line-height: 17px;
  border-radius: 35px;
  cursor: pointer;
  text-align: center;
}

.product-buttons-container:hover {
  background-color: #E5423A;
}
<a href="#" class="product-buttons-container">Click Me To Get There</a>

问题在于,只有文本仍然具有带有目标 URL 的“a”标签。按钮区域只是外观和感觉,尽管在鼠标悬停时光标会随着指针变化,但按钮填充中没有链接。

为了获得完全可点击的按钮,我缺少什么?

标签: htmlcssbutton

解决方案


<a>标签具有display: inline默认值。您可以制作它display: inline-blockdisplay: block调整元素的大小。正如用户 Terry 已经指出的那样,您可以使用来设置光标的样式(尽管如果您使用标签cursor: pointer,则没有必要。)<a>

您可以:

<a>自身设置为按钮

.button-link {
  padding: 10px;
  border-radius: 10px;
  background: silver;
  text-decoration: none;
  color: black;
}
<a href="https://www.google.com" class="button-link">I can be a button, too</a>

<button>用链接元素包裹

.button-link {
  background-color: silver;
}

button {
  border: none;
  padding: 10px;
  border-radius: 10px;
  cursor: pointer;
}
<a href="https://www.google.com" class="button-link"><button>I am clickable</button></a>

<button>与 JS 和 onclick 一起使用(不推荐)

document.body.onload = function() {
  let buttons = document.querySelectorAll('[data-link]');
  for (let i = 0; i < buttons.length; i++) {
    let button = buttons[i];
    button.onclick = function() {
      window.location.href = button.dataset.link;
    }
  }
}();
.button {
  padding: 10px;
  border: none;
  border-radius: 10px;
  background-color: silver;
  cursor: pointer;
}
<button class="button" data-link="https://www.google.com">I am a link, too</button>

您甚至不必使用<a>,或者<button>您可以链接您喜欢的任何元素。您始终可以在 javascript 中添加带有该onclick属性的链接。

这是更大范围内的链接:

.button {
  display: inline-block;
  margin: 0 20px;
  width: 100px;
  padding: 10px;
  border: 2px solid #333;
  border-radius: 10px;
  background-color: silver;
  color: #000;
  text-decoration: none;
}

.button:hover {
  background-color: #eaeaea;
}
<p>This represents some text on a website la-di-da
  <a class="button" href="#">this whole box shall be linked and act like a button</a> and after the link it just goes on ...
</p>
<p>Some other paragraph</p>


推荐阅读