这里用到css3的过渡transition(在点击图片之前,鼠标移入图片,0.7s改变了图片的透明度;进入模态效果,鼠标移入关闭按钮时,0.5s显示了关闭按钮背景颜色)和动画animation(给模态框加上动画,比例大小从0变到1)。
html代码:
<!DOCTYPE html>
<html lang="en"><head>
<meta charset="UTF-8">
<title>模态框</title>
<style>
#img1{
display: block;
margin:100px auto 0;
border-radius: 5px;
cursor:pointer;
transition:0.7s;
/*css3过渡*/
}
#img1:hover{
opacity: 0.8;
}
/*modal样式*/
#modal{
width: 100%;
height: 100%;
position: fixed;
top:0;
left:0;
z-index: 1;
display: none;
background-color: rgba(0,0,0,0.9);
padding-top: 100px;
animation:myanimation 0.5s;
-webkit-animation:myanimation 0.5s;
}
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
#close{
position: absolute;
right:35px;
top:15px;
color:#f1f1f1;
font-size: 40px;
font-weight: bold;
transition:0.5s;
}
#close:hover,#close:focus{
background-color: #bbb;
cursor: pointer;
}
/*增加动画animation*/
@keyframes myanimation{
from{transform:scale(0) }
to{transform:scale(1);}
}
@-webkit-keyframes myanimation{
form{-webkit-transform:scale(0.1);}
to{-webkit-transform:scale(1);}
}
#img2{
animation:myanimation 0.5s;
-webkit-animation:myanimation 0.5s;
}
</style>
</head>
<body>
<img src="6.jpg" alt="模态框" id="img1">
<div id="modal">
<span id="close">×</span>
<img id="img2" class="modal-content">
</div>
</body>
</html>
javascript代码:
<script>
window.onload=function(){
var oModal=document.getElementById('modal');
var oImg1=document.getElementById('img1');
var oImg2=document.getElementById('img2');
var oClose=document.getElementById('close');
oImg1.onclick=function(){
oModal.style.display='block';
oImg2.src=this.src;
}
oClose.onclick=function(){
oModal.style.display='none';
}
}
</script>