如何为HTML/CSS切换按钮的BN/EN选项添加跳转链接
解决方案:为语言切换按钮的BN/EN添加独立跳转链接
要实现点击BN跳转至google.com、点击EN跳转至facebook.com的需求,你需要调整HTML结构并修改对应的CSS样式,具体步骤如下:
1. 修改HTML结构
将原来的<span>标签替换为<a>标签,添加对应的跳转链接:
<div class="switch"> <input id="language-toggle" class="check-toggle check-toggle-round-flat" type="checkbox" /> <label for="language-toggle"></label> <a href="https://google.com" class="on">BN</a> <a href="https://facebook.com" class="off">EN</a> </div>
2. 调整CSS样式
由于原来的样式针对<span>标签,且设置了pointer-events: none(禁止点击),需要修改选择器并移除该属性,确保链接可点击:
.switch { position: relative; display: inline-block; margin: 0 5px; } /* 将选择器从span改为a,移除pointer-events: none */ .switch > a { position: absolute; top: 14px; font-family: 'Helvetica', Arial, sans-serif; font-weight: bold; font-size: 12px; text-transform: uppercase; text-shadow: 0 1px 0 rgba(0, 0, 0, .06); width: 50%; text-align: center; color: inherit; text-decoration: none; /* 移除链接默认下划线 */ } input.check-toggle-round-flat:checked ~ .off { color: #F36F25; } input.check-toggle-round-flat:checked ~ .on { color: #fff; } .switch > a.on { left: 0; padding-left: 2px; color: #F36F25; } .switch > a.off { right: 0; padding-right: 4px; color: #fff; } .check-toggle { position: absolute; margin-left: -9999px; visibility: hidden; } .check-toggle + label { display: block; position: relative; cursor: pointer; outline: none; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } input.check-toggle-round-flat + label { padding: 2px; width: 97px; height: 35px; background-color: #F36F25; -webkit-border-radius: 60px; -moz-border-radius: 60px; -ms-border-radius: 60px; -o-border-radius: 60px; border-radius: 60px; } input.check-toggle-round-flat + label:before, input.check-toggle-round-flat + label:after { display: block; position: absolute; content: ""; } input.check-toggle-round-flat + label:before { top: 2px; left: 2px; bottom: 2px; right: 2px; background-color: #F36F25; -moz-border-radius: 60px; -ms-border-radius: 60px; -o-border-radius: 60px; border-radius: 60px; } input.check-toggle-round-flat + label:after { top: 4px; left: 4px; bottom: 4px; width: 48px; background-color: #fff; -webkit-border-radius: 52px; -moz-border-radius: 52px; -ms-border-radius: 52px; -o-border-radius: 52px; border-radius: 52px; -webkit-transition: margin 0.2s; -moz-transition: margin 0.2s; -o-transition: margin 0.2s; transition: margin 0.2s; } input.check-toggle-round-flat:checked + label { } input.check-toggle-round-flat:checked + label:after { margin-left: 44px; }
关键改动说明
- 将
<span>替换为<a>标签,直接添加跳转链接,符合HTML语义化规范 - 移除了
.switch > span中的pointer-events: none属性,确保链接可以被点击 - 为
<a>标签添加text-decoration: none和color: inherit,保持原有的视觉样式,避免链接默认下划线和颜色干扰 - 所有针对
<span>的CSS选择器替换为<a>,保证样式正常生效
内容的提问来源于stack exchange,提问作者Heri Irawan
相关产品推荐
相关产品推荐

