html无卡顿动画实现——requestAnimationFrame

时间:2023-03-08 23:50:46
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>