1.tab切换
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{margin: 0;padding: 0;}
ul li{list-style: none}
.box{margin:100px auto;border: 1px solid #ddd;width: 350px;height: 300px;overflow: hidden;}
.mt span{display: inline-block;width: 87px; height: 30px;line-height: 30px;text-align: center;margin-left: -3px;cursor: pointer}
.mt span.current{background: #FFAC91;}
.mb li{width: 100%;height: 300px;background: #FFAC91;display: none;}
.mb li.show{display: block;}
</style>
</head>
<body>
<div class="box">
<div class="mt">
<span class="current">tab1</span>
<span>tab2</span>
<span>tab3</span>
<span>tab4</span>
</div>
<div class="mb">
<ul>
<li class="show">tab1</li>
<li>tab2</li>
<li>tab3</li>
<li>tab4</li>
</ul>
</div>
</div>
<script>
var spans=document.getElementsByTagName("span");
var lis=document.getElementsByTagName("li");
for(var i=0;i<spans.length;i++){
spans[i].index=i;
spans[i].onmouseover=function(){
//清除所有的span类
for(var j=0;j<spans.length;j++){
spans[j].className="";
lis[j].className="";
}
this.className="current";
lis[this.index].className="show"
}
}
</script>
</body>
</html>
var spans=document.querySelectorAll(".mt>span");
var lis=document.querySelectorAll(".mb>li");
for(var i=0;i<spans.length;i++){ //给每个span添加click事件
spans[i].index=i;
spans[i].addEventListener("click",function(){
for(var j=0;j<spans.length;j++){ //清除span和li的所有类
spans[j].classList.remove("current");
lis[j].classList.remove("show");
}
this.classList.add("current");
lis[this.index].classList.add("show");
});
}
预览
2.模态框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.btn{
padding: 5px 15px;
background: #6A6AFF;
color: #fff;
border: none;
}
.dialog-bg{
position: fixed;
top: 0;
right: 0;
left: 0;
bottom: 0;
background: rgba(0,0,0,.5);
display: none;
}
.dialog-ct{
position: absolute;
left: 50%;
top: 50%;
margin-top: -100px;
margin-left: -150px;
height: 200px;
width: 300px;
background: #fff;
text-align: center;
}
.head h3{
border-bottom: 1px solid;
text-align: center;
}
.head >a{
position: absolute;
top: 15px;
right: 15px;
text-decoration: none;
font-size: 16px;
}
.show{display: block}
</style>
</head>
<body>
<button class="btn">点我</button>
<div class="dialog-bg">
<div class="dialog-ct">
<div class="head">
<h3>标题标题 </h3>
<a href="javascript:;" id="close">X</a>
</div>
<div class="content">
<p>内容</p>
<p>内容2</p>
</div>
</div>
</div>
<script>
var btn=document.querySelector(".btn");
var dialog=document.querySelector(".dialog-bg");
var close=document.querySelector("#close");
var dialogCt=document.querySelector(".dialog-ct");
btn.addEventListener('click',function(){
dialog.classList.add("show");
});
close.addEventListener('click',function(){
dialog.classList.remove("show");
});
dialog.addEventListener('click',function(){
dialog.classList.remove("show");
});
dialogCt.addEventListener('click',function(e){
e.stopPropagation();
})
</script>
</body>
</html>