switch开关兼容IE8时,用button代替checkbox做成switch开关

本文介绍了如何在不支持:before和:checked选择器的IE8中,利用button元素和CSS来创建switch开关效果。通过这种方法,可以确保在IE8及更高版本的浏览器中都能正常显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做switch开关兼容ie浏览器时,遇到了坑,其中的:before选择器和:checked在IE8中不兼容,思来想去,就取了个巧,用button加css做成switch开关。

做成的效果为:IE8:    IE9+:

<!DOCTYPE html> 
<html> 
<head> 
<style type="text/css"> 
.sdm-switch {
  content: attr(data-content);
  font-size: 12px;
  background-color: #5bc0de;
  width: 72px;
  height: 27px;
  position: relative;
  border: 1px solid #46b8da;
  box-shadow: #dfdfdf 0 0 0 0 inset;
  border-radius: 20px;
  border-top-left-radius: 20px;
  border-top-right-radius: 20px;
  border-bottom-left-radius: 20px;
  border-bottom-right-radius: 20px;
  display: inline-block;
  -webkit-appearance: none;
  user-select: none;
  outline: none;
  } 
  .sdm-stch {
    content: attr(data-content);
    font-size: 12px;
    background-color: #dfdfdf;
    width: 72px;
    height: 27px;
    position: relative;
    border: 1px solid #dfdfdf;
    box-shadow: #46b8da 0 0 0 0 inset;
    border-radius: 20px;
    border-top-left-radius: 20px;
    border-top-right-radius: 20px;
    border-bottom-left-radius: 20px;
    border-bottom-right-radius: 20px;
    display: inline-block;
    -webkit-appearance: none;
    user-select: none;
    outline: none;
    }         
.sdm-switch-before  {   
  top:1px;
  width: 54px;
  height: 25px;
  color: black;
  background-color:  #fff;
  border-color:  #fff;
  }
.sdm-switch-after  {
  top:1px;
  left:17px;
  width: 54px;
  height: 25px;
  color: black;
  background-color:  #fff;
  border-color:  #fff;
  }
</style> 
<script type="text/javascript" > 


function SwitchBOT(){
var switchBtn=document.getElementById('SwitchBotton');
var poiSwitch=document.getElementById('PoiSwitch');
if(switchBtn.className=="sdm-switch sdm-switch-before"){
console.log("事件一");
poiSwitch.className=poiSwitch.className.replace("switch","stch"); 
switchBtn.className = switchBtn.className.replace("before", "after");
return false;
}else{
console.log("事件二");
poiSwitch.className=poiSwitch.className.replace("stch","switch"); 
switchBtn.className = switchBtn.className.replace("after", "before");
return false;
}
}
</script> 
</head> 
<body> 
<div class="sdm-switch" id="PoiSwitch" aria-haspopup='true' aria-expanded='false' style="position:absolute;right:160px;top:14px;zIndex:999;">
<BUTTON class="sdm-switch sdm-switch-before" id=SwitchBotton type=button οnclick="SwitchBOT()">Button</BUTTON>
</div>
</body> 
</html> 

代码可直接拷贝使用查看效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值