JavaScript完成动画程序
1,效果图:
以上是纯CSS+JavaScript实现的。点击关闭按钮可以动态关闭这个方框。兼容IE/FF/Chrome。这样的效果如果用jquery实现起来必须是So Easy的,但是我想通过这段代码表达用JavaScript实现动画过程也是很简单的。
2,实现过程:
2.1 基础html代码
以上是纯CSS+JavaScript实现的。点击关闭按钮可以动态关闭这个方框。兼容IE/FF/Chrome。这样的效果如果用jquery实现起来必须是So Easy的,但是我想通过这段代码表达用JavaScript实现动画过程也是很简单的。
2,实现过程:
2.1 基础html代码
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title>14-10-8</title>
</head>
<body>
<div id="error" style="width: 600px;height: 400px;">
<div class="close" id="button">×</div>
</div>
</body>
</html>
2.2 CSS实现总体样式
实现的有:
1) 展示一个有背景颜色的DIV。
2)在div的右上角添加一个"关闭"按钮。这个"关闭"按钮不是用图片实现的,所以添加了很多的样式控制这个按钮。
3)给这个关闭按钮添加了一个光标进入的事件。兼容IE/FF/Chrome。当鼠标进入后按钮显示圆角背景(不兼容IE8以下)。
#error{
background: #313D44;
width: 600px;
height: 400px;
position: relative;
}
.close{
border:1px solid transparent;
width: 22px;
height: 22px;
line-height: 22px;
text-align: center;
border-radius: 11px;
font-size: 20px;
color: #FFFFFF;
position: absolute;
top: 5px;
right: 5px;
cursor: pointer;
}
.close:hover{
border: 1px solid #000000;
background: mediumvioletred;
color: #F9F9F9;
}
2.3 JavaScript实现动画效果
这段代码实现的功能其实也很简单。就是实现的点击关闭按钮之后动态的关闭背景DIV。
window.onload=function(){
document.getElementById("button").onclick=function(){
// 隐藏按钮
document.getElementById("button").style.display="none";
// 调用动画函数
go();
}
};
function go(){
var newWidth = parseInt(document.getElementById("error").style.width)-30;
var newHeight = parseInt(document.getElementById("error").style.height)-20;
if(newWidth>=0){
document.getElementById("error").style.width=newWidth+"px";
}
if(newHeight>=0){
document.getElementById("error").style.height=newHeight+"px";
}
if(newWidth!=0&&newHeight!=0){
setTimeout(function(){
go();
},10);
}
}
3.全部代码:
<!DOCTYPE html>
<html> <head>
<meta charset="UTF-8">
<title>14-10-8</title>
<style type="text/css">
#error{
background: #313D44;
width: 600px;
height: 400px;
position: relative;
}
.close{
border:1px solid transparent;
width: 22px;
height: 22px;
line-height: 22px;
text-align: center;
border-radius: 11px;
font-size: 20px;
color: #FFFFFF;
position: absolute;
top: 5px;
right: 5px;
cursor: pointer;
}
.close:hover{
border: 1px solid #000000;
background: mediumvioletred;
color: #F9F9F9;
}
</style>
<script>
window.onload=function(){
document.getElementById("button").onclick=function(){
// 隐藏按钮
document.getElementById("button").style.display="none";
go();
}
};
function go(){
var newWidth = parseInt(document.getElementById("error").style.width)-30;
var newHeight = parseInt(document.getElementById("error").style.height)-20;
if(newWidth>=0){
document.getElementById("error").style.width=newWidth+"px";
}
if(newHeight>=0){
document.getElementById("error").style.height=newHeight+"px";
}
if(newWidth!=0&&newHeight!=0){
setTimeout(function(){
go();
},10);
}
}
</script>
</head>
<body>
<div id="error" style="width: 600px;height: 400px;">
<div class="close" id="button">×</div>
</div>
</body>
</html>