<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#square{
width: 100px;
height: 100px;
background: red;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="square">
</div>
<script>
//宽,高,透明度,水平,垂直
var square = document.getElementById("square");
//得到ele元素的attr样式的值,ele:元素,attr:属性
function getCss(ele,attr){
//变量未定义不能直接用,如果想判断一个变量是否存在用typeof
//属性未定义可以直接用
if(typeof getComputedStyle){
return parseFloat(getComputedStyle(ele,null)[attr]);
}else{
return parseFloat(ele.currentStyle[attr]);
}
}
window.onload = function(){
console.log(getCss(square,"height"));//100(number)
}
// 创建move函数
function move(ele,target){
if(getCss(ele,"left")<target){
ele.style.left = getCss(ele,"left")+5+"px";
window.setTimeout(
function(){
move(ele,target);
},30
);
}else if(getCss(ele,"left")>target){
ele.style.left = getCss(ele,"left")-5+"px";
window.setTimeout(
function(){
move(ele,target);
},30
);
}
}
square.onclick=function(){
move(this,600);
}
</script>
</body>
</html>
JavaScript前端实战项目动画实例:动画
最新推荐文章于 2025-03-24 10:30:16 发布