慕仰0443758
2017-02-25 11:18
下面的代码无法实现链式动画是怎么回事,浏览器提示横线有误,这里一直都是这样啊怎么就错了
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
}
JS:
function startMove(obj,attr,target,fn){
clearInterval(obj.timer);
var speed=0;
obj.timer = setInterval(function(){
var icur = 0 ;
if(attr=='opacity'){
icur = Math.round(parseFloat(getStyle(obj,attr))*100);
}else{
icur = parseInt(getStyle(obj,attr));
}
speed = (target-icur)/8;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
if(icur==target){
clearInterval(obj.timer);
if(fn){
fn();
}
}else{
if(attr=='opacity'){
obj.style.opacity = (icur+speed)/100;
obj.style.filter = 'alpha(opacity:'+(icur+speed)+')';
}else{
obj.style[attr] = icur+speed+'px';
}
}
},30);
}
//获取属性
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
}
HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>
</title>
<style type="text/css">
#test{
height: 200px;
width: 200px;
border: 2px solid red;
background: red;
opacity: 0.3;
filter:alpha(opacity:30);
}
</style>
<script src = "linkspeed.js"></script>
<script type="text/javascript">
window.onload = function(){
var test = document.getElementById('test');
test.onmouseover = function(){
startMove(this,'width',400,function(){
startMove(this,'height',400,function(){
startMove(this,'opacity',100);
})
});
}
}
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
startMove(this,'width',400,function(){
startMove(this,'height',400,function(){
startMove(this,'opacity',100);
把后两个this换成你定义的test。
判断 this 指向谁,看执行时而非定义时,只要函数(function)没有绑定在对象上调用,它的 this 就是 window。
你会发现按照你原来的代码写的话,它只变了width,height和opacity都没有变,显示的错误是window.getStyle...,这说明后两个startMove()函数全都去操做window对象了,而不是id为test的div。
JS动画效果
113925 学习 · 1443 问题
相似问题