任意運動框架

Vivian_shuang發表於2016-07-11

<!DOCTYPE html>

<html>


<head>

<meta charset="UTF-8">

<title></title>

<style type="text/css">

div {

width: 200px;

height: 200px;

background-color: aquamarine;

margin: 10px;

border: 10px solid deeppink;

float: left;

text-align: center;

line-height: 200px;

}

#div3 {

opacity: 0.3;

filter: alpha(opacity: 30);

}

</style>

</head>


<body>

<div id="div1">變大</div>

<div id="div2">變寬</div>

<div id="div3">改變透明度</div>


<script type="text/javascript">

var oDiv1 = document.getElementById("div1");

var oDiv2 = document.getElementById("div2");

var oDiv3 = document.getElementById("div3");


oDiv1.onmouseover = function() {

startMove(oDiv1, 100, "fontSize");

}

oDiv1.onmouseout = function() {

startMove(oDiv1, 20, "fontSize");

}

oDiv2.onmouseover = function() {

startMove(oDiv2, 50, "borderWidth");

}

oDiv2.onmouseout = function() {

startMove(oDiv2, 10, "borderWidth");

}

oDiv3.onmouseover = function() {

startMove(oDiv3, 100, "opacity");

}

oDiv3.onmouseout = function() {

startMove(oDiv3, 30, "opacity");

}


function getStyle(obj, name) {

if (obj.currentStyle) {

return obj.currentStyle[name];

} else {

return getComputedStyle(obj, false)[name];

}

}


// function startMove(obj, iTarget, att) {

// clearInterval(obj.timer);

// obj.timer = setInterval(function() {

// // 獲取非行間樣式 當前語速運動的位置

// var offsetCur = parseInt(getStyle(obj, att));

// var speed = (iTarget - offsetCur) / 10;

// speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);

// if (iTarget == offsetCur) {

// clearInterval(obj.timer);

// } else {

// obj.style[att] = offsetCur + speed + 'px';

// }

// }, 20);

// }


// 任意值運動框架

function startMove(obj, iTarget, att, endFn) {

clearInterval(obj.timer);

obj.timer = setInterval(function() {


// 當前元素運動的位置

// var offsetCur = parseInt(getStyle(obj, att));

var offsetCur = 0;

// 判斷是否為透明度

if (att == 'opacity') {

offsetCur Math.round(parseFloat(getStyle(obj, att)) * 100);

} else {

offsetCur = parseInt(getStyle(obj, att));

}


var speed = (iTarget - offsetCur) / 6;

speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);


if (iTarget == offsetCur) {

clearInterval(obj.timer);

if (endFn) {endFn();}

} else {

// 判斷是否為透明度

if (att == 'opacity') {

obj.style.filter = "alpha(opacity:" + (offsetCur + speed) + ")";

obj.style.opacity = (offsetCur + speed) / 100;

} else {

obj.style[att] = offsetCur + speed + 'px';

}

}


}, 20);

}

</script>

</body>


</html>

相關文章