使用 CSS 创建点击事件的最常见方法是使用复选框技巧。
此方法具有广泛的浏览器支持。
我们需要为 <label> 元素添加一个 for 属性,为 <input> 元素添加一个 id 属性。
使用复选框 hack 添加 onclick 事件的示例:
<!DOCTYPE html> <html> <head> <style> label { display: block; background: #dbdbd9; width: 80px; height: 80px; } #box:checked + label { background: #fffc47; color: #666666; } </style> </head> <body> <form action="/form/submit" method="post"> <input type="checkbox" id="box" /> <label for="box">Click here</label> </form> </body> </html>
在上面的例子中,我们对 <input> 标签的 id 属性和 <label> 标签的 for 属性应用了相同的值。
标签 onclick 用 :checked 伪类重新设计。
添加用于调整图像大小的 onclick 事件的示例:
<!DOCTYPE html> <html> <head> <style> #btnControl { display: none; } #btnControl:checked + label > img { width: 150px; height: 170px; } </style> </head> <body> <input type="checkbox" id="btnControl" /> <label class="btn" for="btnControl"> <img src="button.png" id="btnLeft" /> </label> </body> </html>
由于 <label> 元素只能与一个表单控件相关联,因此我们不能只在 <label> 标签内放置一个按钮。
但是我们可以添加一些 CSS 来更改按钮的外观和行为。
在 <input> 标签上添加 onclick 效果的示例:
<!DOCTYPE html> <html> <head> <style> #btnControl { display: none; } .btn { width: 80px; height: 30px; background: #ffffff; border-radius: 7px; padding: 1px 3px; box-shadow: 1px 1px 1px #000000; display: block; text-align: center; background-image: linear-gradient(to bottom, #e8e8e8, #a1a1a1); font-family: arial; font-size: 14px; line-height: 30px; } .btn:hover { background-image: linear-gradient(to bottom, #97e8ae, #3be36b); } .btn:active { margin-left: 1px 1px 0; box-shadow: -1px -1px 1px #000; outline: 1px solid #000000; -moz-outline-radius: 7px; background-image: linear-gradient(to top, #97e8ae, #3be36b); } #btnControl:checked + label { width: 70px; height: 74px; line-height: 74px; } </style> </head> <body> <input type="checkbox" id="btnControl" /> <label class="btn" for="btnControl">Click here</label> </body> </html>
日期:2020-06-02 22:15:04 来源:oir作者:oir