This article mainly introduces the implementation method of JavaScript Buffer motion, briefly analyzes the implementation principle and related computing skills of JavaScript Buffer motion, and provides two example codes for summary and analysis, for more information about how to implement JavaScript Buffer motion, see the example in this article. We will share this with you for your reference. The details are as follows:
Implementation principle(Target distance-current distance)/base = speed (the larger the movement distance, the smaller the speed, the inverse ratio of the movement distance to the speed)
The code is as follows:
(500-oDiv. offsetLeft)/7 = iSpeed;
Note:: An integer is required when the calculated speed is decimal;
The code is as follows:
(500-oDiv. offsetLeft)/7 = iSpeed; iSpeed = iSpeed> 0? Math. ceil (iSpeed): Math. floor (iSpeed );
Example 1: slider Buffering
Buffer motionScript window. onload = function () {var oBtn = document. getElementById ('btn1 '); var oDiv = document. getElementById ('p1'); oBtn. onclick = function () {startMove (oDiv, 300) ;}; var timer = null; function startMove (obj, iTarget) {clearInterval (timer ); timer = setInterval (function () {var iSpeed = (iTarget-obj. offsetLeft)/8; iSpeed = iSpeed> 0? Math. ceil (iSpeed): Math. floor (iSpeed); if (iTarget = obj. offsetLeft) {clearInterval (timer);} else {obj. style. left = obj. offsetLeft + iSpeed + 'px '; }}, 30);} script
Example 2: sliding the sidebar
Slide on the sidebarScript window. onload = window. onscroll = function () {var oDiv = document. getElementById ('p1'); var iScrollTop = document.doc umentElement. scrollTop | document. body. scrollTop; var clientHeight = document.doc umentElement. clientHeight; var iH = (clientHeight-oDiv. offsetHeight)/2 + iScrollTop; // oDiv. style. top = iH + 'px '; startMove (oDiv, parseInt (iH) ;}; var timer = null; function startMove (obj, iTar Get) {clearInterval (timer); timer = setInterval (function () {var iSpeed = (iTarget-obj. offsetTop)/8; iSpeed = iSpeed> 0? Math. ceil (iSpeed): Math. floor (iSpeed); if (obj. offsetTop = iTarget) {clearInterval (timer);} else {obj. style. top = obj. offsetTop + iSpeed + 'px '; }}, 30);} script