在做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>
代码可直接拷贝使用查看效果。