zoukankan      html  css  js  c++  java
  • Javascript加速运动与减速运动

    加速运动,即一个物体运动时速度越来越快;减速运动,即一个物体运动时速度越来越慢。现在用Javascript来模拟这两个效果,原理就是用setInterval或setTimeout动态改变一个元素与另外一个元素的距离,如xxx.style.left或xxx.style.marginLeft,然后每次运动后都使速度增加,这样加速运动的效果就出现了,减速运动是同样的道理。

    下面是两个示例:

    加速运动

    [html]

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Javascript加速运动</title>
    <style type="text/css">
    * {margin: 0; padding: 0;}
    .div1 { 100px; height: 100px; background: #f60 url(qiuweiguan.gif) no-repeat center center;}
    </style>
    <script type="text/javascript">
    var $$ = function (id) {
    return document.getElementById(id);
    }

    window.onload = function () {
    var oBtn = $$("btn1");
    var oDiv = $$("div1");
    var timer = null;
    var speed = 0;
    oBtn.onclick = function () {
    clearInterval(timer);
    timer = setInterval(function () {
    speed ++;
    oDiv.style.marginLeft = oDiv.offsetLeft + speed + "px";
    }, 30);
    }
    }
    </script>
    </head>
    <body id = "body">
    <button id="btn1" class="btn1">GO</button>
    <div id="div1" class="div1"></div>
    </body>
    </html>

    [/html]

    加速运动的示例演示及源码下载

           

    注:本示例中,点击GO后,div块会一直向右做加速运动

    减速运动

    [html]

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Javascript减速运动</title>
    <style type="text/css">
    * {margin: 0; padding: 0;}
    .div1 { 100px; height: 100px; background: #f60 url(qiuweiguan.gif) no-repeat center center;}
    </style>
    <script type="text/javascript">
    var $$ = function (id) {
    return document.getElementById(id);
    }

    window.onload = function () {
    var oBtn = $$("btn1");
    var oDiv = $$("div1");
    var timer = null;
    var speed = 30;
    oBtn.onclick = function () {
    clearInterval(timer);
    timer = setInterval(function () {
    speed — ;
    oDiv.style.marginLeft = oDiv.offsetLeft + speed + "px";
    }, 30);
    }
    }
    </script>
    </head>
    <body id = "body">
    <button id="btn1" class="btn1">GO</button>
    <div id="div1" class="div1"></div>
    </body>
    </html>

    [/html]

    减速运动的示例演示及源码下载

           

    注:本示例中,点击GO后,div块会一直向右做减速运动,直到速度减为零后,速度变为负值,再向左做加速运动

  • 相关阅读:
    现代软件工程_第一周练习_第12题
    [assembly: AssemblyVersion("1.0.1.*")] 指定版本字符串不符合所需格式
    C#中结构体与字节流互相转换
    字节转化为结构体BytesToStruct
    C#调用Microsoft.DirectX.DirectSound问题记录及解决
    C# Wpf集合双向绑定
    <转载>XML操作
    <转载>提升程序的特权(AdjustTokenPrivileges)
    <转载>批处理之FOR语句祥解
    Effective STL 笔记: Item 6--Be alert for C++'s most vexing parse
  • 原文地址:https://www.cnblogs.com/ranran/p/4155338.html
Copyright © 2011-2022 走看看