html无卡顿动画实现——requestAnimationFrame
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div style="width:50px; height:50px; background-color:red;margin-left:2px;">
文字
</div>
</body>
</html>
<script>
var px = 5;
var myReq;
function test() {
var div = document.querySelector('div');
div.style.marginLeft = (parseInt(div.style.marginLeft.replace('px', '')) + px) + 'px';
//if (parseInt(div.style.marginLeft.replace('px', '')) > 500) {
// px = -px;
//}
//if (parseInt(div.style.marginLeft.replace('px', '')) <= 0) {
// px = -px;
//}
if (parseInt(div.style.marginLeft.replace('px', '')) > 500) {
//window.cancelAnimationFrame(myReq);
return;
}
myReq = window.requestAnimationFrame(test);
}
myReq = window.requestAnimationFrame(test);
</script>
岁月无情催人老,请珍爱生命,远离代码!!!

浙公网安备 33010602011771号