这篇文章主要介绍了 JavaScript 缓冲运动实现方法, 简单分析了 JavaScript 缓冲运动的实现原理与相关运算技巧, 并给出了两则实例代码予以总结分析, 需要的朋友可以参考下
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
本文实例讲述了 JavaScript 缓冲运动实现方法。分享给大家供大家参考,具体如下:
实现原理:(目标距离 - 当前距离) / 基数 = 速度 (运动距离越大速度越小,运动距离和速度成反比)
- (500 - oDiv.offsetLeft) / 7 = iSpeed;
需要注意:当计算出来的速度有小数时需要取整;
- (500 - oDiv.offsetLeft) / 7 = iSpeed;
- iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
例子 1:滑块缓冲运动
- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>
- 缓冲运动
- </title>
- <style>
- #div1{ width:100px; height:100px; background:red; position:absolute; top:50px;
- left:0;} span{ width:1px; height:300px; background:black; position:absolute;
- left:300px; top:0; display:block;}
- </style>
- <script>
- window.onload = function() {
- var oBtn = document.getElementById('btn1');
- var oDiv = document.getElementById('div1');
- 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>
- </head>
- <body>
- <input id="btn1" type="button" value="移动" />
- <div id="div1">
- </div>
- <span>
- </span>
- </body>
- </html>
例子 2:侧边栏滑动
- <!doctype html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>
- 侧边栏滑动
- </title>
- <style>
- #div1{ width:100px; height:100px; background:red; position:absolute; right:0;
- top:0;}
- </style>
- <script>
- window.onload = window.onscroll = function() {
- var oDiv = document.getElementById('div1');
- var iScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
- var clientHeight = document.documentElement.clientHeight;
- var iH = (clientHeight - oDiv.offsetHeight) / 2 + iScrollTop;
- //oDiv.style.top = iH + 'px';
- startMove(oDiv, parseInt(iH));
- };
- var timer = null;
- function startMove(obj, iTarget) {
- 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>
- </head>
- <body style="height:2000px;">
- <div id="div1">
- </div>
- </body>
- </html>
希望本文所述对大家 JavaScript 程序设计有所帮助。
来源: http://www.phperz.com/article/17/0218/267666.html