甫里
2016-04-18 22:30:53
window.onload=Move;
function?getStyle(obj,attr){
if?(obj.currentStyle)?{
return?obj.currentStyle;
}else{
return?getComputedStyle(obj,false)[attr];
}
}
function?Move(){
var?box=document.getElementById("Box"),
box2=document.getElementById("Box2"),
box3=document.getElementById("Box3")
box.onmouseover=function(){
MoveModelFn(this,{"width":600});
}
box.onmouseout=function(){
MoveModelFn(this,{"width":400});
}
//同時(shí)運(yùn)動
box2.onmouseover=function(){
var?_this=this;
MoveModelFn(_this,{"opacity":100,"width":800});//為什么最后到達(dá)不了width?800
}
box2.onmouseout=function(){
MoveModelFn(this,{"opacity":30,"width":400});//為什么也恢復(fù)到達(dá)不了width?400
}
box3.onmouseover=function(){
var?_this=this;
MoveModelFn(_this,{"height":300},function(){
MoveModelFn(_this,{'width':600})
});
}
box3.onmouseout=function(){
var?_this=this;
MoveModelFn(_this,{"height":200});
}
}
//function?MoveModelFn(obj,{attr:iTarget},fn)
function?MoveModelFn(obj,json,fn){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var?flag=true;
for(var?attr?in?json){
//獲取屬性值
var?icur=0;
if?(attr?==?'opacity')?{
icur?=Math.round(parseFloat(getStyle(obj,attr))*100);
}else{
icur=parseInt(getStyle(obj,attr));
}
//設(shè)置速度
var?speed=(json[attr]-icur)/10;
var?speed=speed>0?Math.ceil(speed):Math.floor(speed);
//?判斷停止
if(icur?!=?json[attr]){
flag=false;
}
if?(attr?==?'opacity')?{
obj.style.filter='alpha(opacity:'+(icur+speed)+')';//icur原始值+變化值speed
obj.style.opacity=(icur+speed)/100;
}else{
obj.style[attr]=icur+speed+"px";
console.log(obj.style[attr]);
}
if(flag){
clearInterval(obj.timer);
//?回調(diào)函數(shù)
if(fn)?{
fn();
}
}
}
},30)
} <!DOCTYPE?html>
<html>
<head>
<meta?charset="UTF-8">
<title>MoveModel</title>
<link?rel="stylesheet"?type="text/css"?href="style/MoveModelCss.css">
</head>
<body>
<div?id="Box"></div>
<div?id="Box2"></div>
<div?id="Box3"></div>
<script?src="js/MoveModelJs.js"></script>
</body>
</html>body{
margin:?0;
padding:?0;
}
div{
height:?200px;
width:?400px;
background:?yellow;
border:2px?solid?green;
margin-bottom:?10px;
filter:?alpha(opacity:30);
opacity:?0.3;
}
6 回答
已采納

smartone
TA貢獻(xiàn)1條經(jīng)驗(yàn) 獲得超0個(gè)贊
把speed=(json[attr]-icur)/6;,
第67行的if(flag){}放在整個(gè)for in循環(huán)的外面.
已試,可以了

淡淡的月餅
TA貢獻(xiàn)8條經(jīng)驗(yàn) 獲得超0個(gè)贊
opacity和width中任意一個(gè)值達(dá)到了目標(biāo),就會停止運(yùn)動。你把判斷改成當(dāng)所有的值都到達(dá)了,才停止運(yùn)動就行啦

qq_青棗工作室_0
TA貢獻(xiàn)446條經(jīng)驗(yàn) 獲得超754個(gè)贊
你的box2有兩個(gè)屬性opacity和width都在變化。而在width未達(dá)到800前,opacity就已經(jīng)先達(dá)到了100值,進(jìn)而判斷到停止了,即flag為true,?clearInterval(obj.timer);
你的speed值是整數(shù),多個(gè)屬性同時(shí)變化時(shí),會出現(xiàn)比較大的誤差,不能同時(shí)到達(dá)最終值。
添加回答
舉報(bào)
0/150
提交
取消