html - 如何有一个可点击的按钮
问题描述
我有一个文本链接作为“点击我到达那里”,我通过 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”标签。按钮区域只是外观和感觉,尽管在鼠标悬停时光标会随着指针变化,但按钮填充中没有链接。
为了获得完全可点击的按钮,我缺少什么?
解决方案
该<a>
标签具有display: inline
默认值。您可以制作它display: inline-block
或display: 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>
推荐阅读
- c - C 中的局部作用域
- debian - Google 云计算实例(启用 oslogin)如何与“/etc/passwd”、“/etc/group”等集成?
- database - 是双表Oracle管理的表空间还是用户管理的表空间
- docker - docker compose 推送到 docker hub
- sql - SQL删除重复查询
- javascript - 为什么新日期在 Firefox 浏览器中不起作用
- python - 如何以日期为 x 轴计算回归?
- json - 是否可以在 Code First Entity Framework 中使用 JSON 文件作为后端存储?
- php - 不知道出了什么问题 在 UBUNTU 上安装了 LETSENCRYPT、NGINX、PHP 和 MYSQL
- r - 在 for 循环中使用列表而不是 r 中的 rbind