下面例子只是写了个上下移动的情况,对于左右移动,以及其他变换(translate、translate3d、translateZ、scale、rotate、skew等)也是同样的思路,自行去实现。
<!DOCTYPE html>
<html lang="cmn-Hans-CN">
<head>
<meta charset="UTF-8">
<title>移动</title>
<style type="text/css">img{ width: 600px; height: 500px; transform: translateY(0%); }</style></head>
<body>
<img src="https://thumbnail0.baidupcs.com/thumbnail/4fa75095956981d05a6734c74061574d?fid=3625100479-250528-1061463673340593&time=1540177200&rt=sh&sign=FDTAER-DCb740ccc5511e5e8fedcff06b081203-s5ypdnWCXm4YUYJ1JUTL93FW5JQ%3D&expires=8h&chkv=0&chkbd=0&chkpc=&dp-logid=9135203299536056708&dp-callid=0&size=c710_u400&quality=100&vuk=-&ft=video">
<input type="button" value="开始" name="beginFunc" onclick="beginFunc();">
<input type="button" value="暂停" name="pauseFunc" onclick="pauseFunc();">
</body>
<script type="text/javascript">
var num = 0;
var pause = 0;
var pauseFlag = 0;
var beginFlag = 0;
var img = document.getElementsByTagName('img')[0];
var speed = 0.05; // 速度,此值越小,速度越快(最好用0.1、0.2、0.5、0.01、0.02、0.05……这样的数据)
var intervalNum = 0.1;
var set = null;
function startMove() {
set = setInterval('change()', intervalNum / speed);
}
function change() {
if (num < 0 || num > 100) {
return;
}
if (num >= 0.1 && num <= 100) {
img.style.transform = "translateY(" + num + "%)";
num = num + 0.1;
}
//console.log("num=",num,"pauseFlag=",pauseFlag)
}
function beginFunc() {
if (beginFlag == 0) { //从别的状态(页面开始或者暂停)而来
if (num == 0 && pauseFlag == 0) { //flagzt等于0是从页面载入状态进入移动
num = 0.1;
} else {
num = pause; //把当前暂停时位置给num从num再开始移动
pauseFlag = 0; //证明当前不是暂停状态了
}
beginFlag = num;
}
startMove();
//console.log(pause);
}
function pauseFunc() {
if (pauseFlag != 0) { //flagzt不等于0证明当前是暂停状态,再点击暂停还是设置当前状态
img.style.transform = "translateY(" + pause + "%)";
} else {
if (num < 0 || num > 100) {
return;
}
//console.log("暂停num="+num)
pause = num;
pauseFlag = num;
num = 0;
img.style.transform = "translateY(" + pause + "%)";
}
beginFlag = 0;
clearInterval(set);
}
</script>
</html>