js原⽣实现toggle()css
<style>
.show{
opacity: 0;
visibility: hidden;
transition: all 2s linear;
background: red;
}
.hide{
visibility: visible;
transition: all 2s linear;
background: blue;
}
#box{
border: 1px solid #222;
width: 500px;
height: 80px;
text-align: center;
line-height: 80px;
background: red;
}
</style>
<div id="show">显⽰/隐藏</div>
<div id="box">
hello world!
</div>
var show =ElementById('show');
var box =ElementById('box');
show.addEventListener('click',function(){
if(hasClass(box, 'show')){
removeClass(box,'show');
addClass(box,'hide');
}else{
removeClass(box,'hide');
addClass(box,'show');
}
})
alert('s');
}
function addClass(el, className) {
if (hasClass(el, className)) {
return
}
let newClass = el.className.split(' ')
newClass.push(className)
el.className = newClass.join(' ')
borderbox}
function hasClass(el, className) {
// \s匹配任何空⽩字符,包括空格、制表符、换页符等等
let reg = new RegExp('(^|\\s)' + className + '(\\s|$)')
st(el.className)
}
function removeClass(el, className){
if (!hasClass(el, className)) {
return
}
let newClass = el.className.split(' ')
newClass.forEach(function(val, index, newClass){ if(val === className){
newClass.splice(index,1);
}
})
el.className = newClass.join(' ')
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论