JavaScript编程艺术-第10章-10.2-实用的动画

10.2-实用的动画

***代码亲测可用***

HTML:

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8"/>
        <title>LIST</title>
        <script type="text/javascript" src="script/01.js"></script>
        <style type="text/css" media="screen">
            @import url("01.css");
        </style>
    </head>
    <body >
        <h1>Web Design</h1>
        <p>There are the things you should know.</p>
        <ol id="linklist">
            <li><a href="http://www.baidu.com">Structure</a></li>
            <li><a href="http://www.baidu.com">Presentation</a></li>
            <li><a href="http://www.baidu.com">Bechavior</a></li>
        </ol>
    </body>
</html>

JS:

function prepareSlideshow(){
    var slideshow = document.createElement("div");
    slideshow.setAttribute("id", "slideshow");
    
    var preview = document.createElement("img");
    preview.setAttribute("src","img/j.jpg");
    preview.setAttribute("alt", "edsvfdc");
    preview.setAttribute("id", "preview");
    slideshow.appendChild(preview);
    
    preview.style.position = "absolute";
    preview.style.left = "0px";
    preview.style.top = "0px";
    
    var list = document.getElementById("linklist");
    insertAfter(slideshow, list);
    
    var links = list.getElementsByTagName("a");
    links[0].onmouseover = function(){
        moveElement("preview",-100,0,10);
    }
    links[1].onmouseover = function(){
        moveElement("preview",-200,0,10);
    }
    links[2].onmouseover = function(){
        moveElement("preview",-300,0,10);
    }
}

function moveElement(elementID,final_x,final_y,interval){
    var elem = document.getElementById(elementID);
    if(elem.movement){
        clearTimeout(elem.movement);
    }
    
    var xpos = parseInt(elem.style.left);
    var ypos = parseInt(elem.style.top);
    
    if(xpos == final_x && ypos == final_y) return true;
    if(xpos>final_x){
        xpos--;
    }
    if(xpos<final_x){
        xpos++;
    }
    if(ypos>final_y){
        ypos--;
    }
    if(ypos<final_y){
        ypos++;
    }
    elem.style.left = xpos + "px";
    elem.style.top = ypos + "px";
    var repeat = "moveElement('"+elementID+"',"+final_x+","+final_y+","+interval+")";
    elem.movement = setTimeout(repeat, interval);
}

function addLoadEvent(func){
    var oldonload = window.onload;
    if (typeof window.onload != "function"){
        window.onload = func;
    }else{
        window.onload = function(){
            oldonload();
            func();
        }
    }
}

function insertAfter(newElement, targetElement){
    var parent = targetElement.parentNode;
    if(parent.lastChild == targetElement){
        parent.appendChild(newElement);
    }else{
        parent.insertBefore(newElement, targetElement.nextSibling);
    }
}

addLoadEvent(prepareSlideshow);

CSS:

#slideshow{
    width: 100px;
    height: 100px;
    position: relative;
    overflow: hidden;
}

***end***

原文地址:https://www.cnblogs.com/sunshine-blog/p/7065258.html