기본 JS 캐러셀 렌더링의 애니메이션 효과(코드 포함)

不言
풀어 주다: 2018-08-22 17:31:17
원래의
3144명이 탐색했습니다.

이 기사의 내용은 네이티브 js 캐러셀 렌더링의 애니메이션 효과에 관한 것입니다. 이는 특정 참조 가치가 있습니다. 도움이 필요한 친구들이 참고할 수 있기를 바랍니다.

Native JS-Carousel
오늘은 Native JS로 작성된 캐러셀 JS 효과를 작성해봤습니다.
구현 원리:
1. 배열을 만들고 각 그림에 해당하는 z-색인, 불투명도, 상단, 너비를 작성합니다.
2. 회전을 구현하는 작업은 첫 번째 값 세트를 입력하는 것입니다. 생성된 배열을 버튼을 클릭하면 마지막 그룹이 한 번 실행됩니다.
디스플레이 렌더링:
기본 JS 캐러셀 렌더링의 애니메이션 효과(코드 포함)
html 레이아웃:

<p class="wrap" id="wrap">
    <p class="slide" id="slide">
        <ul>
            <li><a href=""><img src="images/logo.png" width="900"    style="max-width:90%" alt=""></a></li>
            <li><a href=""><img src="images/slide.jpg" width="900"    style="max-width:90%" alt=""></a></li>
            <li><a href=""><img src="images/slide2.jpg" width="900"    style="max-width:90%" alt=""></a></li>
            <li><a href=""><img src="images/i1.jpg" width="900"    style="max-width:90%" alt=""></a></li>
            <li><a href=""><img src="images/sto.jpg" width="900"    style="max-width:90%" alt=""></a></li>
        </ul>
        <p class="arrow" id="arrow">
            <a href="javascript:;" id="arrLeft" class="prev"></a>
            <a href="javascript:;" id="arrRight" class="next"></a>
        </p>
    </p></p>
로그인 후 복사

css 스타일:

* {            margin: 0;            padding: 0;        }

        ul {            list-style: none;        }

        .wrap {            width: 1200px;            margin: 100px auto;        }

        .slide {            height: 500px;            position: relative;            width: 1200px;        }

        .slide ul li {            position: absolute;            top: 0;            left: 0;            z-index: 1;        }

        .slide li img {            width: 100%;        }

        .arrow {            position: absolute;            width: 100%;            top: 50%;            opacity: 0;            z-index: 3;        }

        .prev,        .next {            position: absolute;            height: 110px;            width: 110px;            border-radius: 50%;            top: 50%;            //margin-top: -56px;            overflow: hidden;            text-decoration: none;        }
        .prev{            left: 0;            background: url("images/slider-icons.png") no-repeat left top;        }
        .next{            right: 0;            background: url("images/slider-icons.png") no-repeat right top;        }
로그인 후 복사

JS 부분:
다음으로 먼저 해당 이미지의 스타일을 배열에 저장합니다.

//写每张图片对应的样式
    var config = [
        {            "width": 400,            "top": 20,            "left": 50,            "opacity": 0.2,            "zIndex": 2
        },      //0
        {            "width": 600,            "top": 70,            "left": 0,            "opacity": 0.8,            "zIndex": 3
        },     //1
        {            "width": 800,            "top": 100,            "left": 200,            "opacity": 1,            "zIndex": 4
        },     //2
        {            "width": 600,            "top": 70,            "left": 600,            "opacity": 0.8,            "zIndex": 3
        },    //3
        {            "width": 400,            "top": 20,            "left": 750,            "opacity": 0.2,            "zIndex": 2
        }    //4
    ];
로그인 후 복사

페이지가 로딩되면 사진들이 흩어지게 되는데, 즉 방금 생성한 배열을 호출하여 각 사진에 하나씩 할당해 줍니다

var list=my$("slide").getElementsByTagName("li"); //拿到所有li
        function assign() {    //分配函数
            for (var i=0;i<list.length;i++){
                animate(list[i],config[i],function () {
                    flag=true;
                });
            }
        }
        assign();
로그인 후 복사

마우스가 들어가고 나갈 때 왼쪽과 오른쪽 화살표가 버튼을 클릭하면 첫 번째 배열이 마지막으로, 마지막 그룹이 첫 번째로 변경되는 것이 원칙입니다. 플래그는 다음 회전 애니메이션이 계속되기 전에 애니메이션 세트가 완료되도록 버튼을 클릭하는 시점을 제어하는 ​​것입니다.

//鼠标进入,左右焦点的p显示
        my$("wrap").onmouseover=function () {
            animate(my$("arrow"),{"opacity":1});
        };        //鼠标离开,左右焦点的p隐藏
        my$("wrap").onmouseout=function () {
            animate(my$("arrow"),{"opacity":0});
        };        //点击右边按钮事件
        my$("arrRight").onclick=function () {
            if (flag){
                flag=false;
                config.push(config.shift());     //把第一组值放到最后一组

                assign();
            }

        };        //点击左边按钮事件
        my$("arrLeft").onclick=function () {
            if (flag){
                flag=false;
                config.unshift(config.pop());   //把最后一组值放到第一组
                assign();
            }
        };
    };
로그인 후 복사

완전한 JS 코드:

<script>
    //变速动画函数
    function animate(element, json, fn) {
        clearInterval(element.timeId);   //清理定时器
        element.timeId = setInterval(function () {
            var flag = true;    //假设默认为当前值已经等于目标值
            for (var arrt in json) {                if (arrt == "opacity") {   //如果属性值为opacity
                    var current = getStyle(element, arrt) * 100;   //current和target先扩大100倍
                    target = json[arrt] * 100;                    var step = (target - current) / 10;
                    step = step > 0 ? Math.ceil(step) : Math.floor(step);
                    current += step;
                    element.style[arrt] = current / 100;   //运算完后缩小100倍
                } else if (arrt == "zIndex") {   //如果属性值为zindex
                    element.style[arrt] = json[arrt];
                } else {      //普通属性
                    var current = parseInt(getStyle(element, arrt));
                    target = json[arrt];                    var step = (target - current) / 10;
                    step = step > 0 ? Math.ceil(step) : Math.floor(step); //step大于零向上取整,小于零向下取整
                    current += step;
                    element.style[arrt] = current + "px";
                }                if (current != target) {
                    flag = false;
                }
            }            if (flag) {    //只有所有属性的当前值已经等于目标值,才清理定时器
                clearInterval(element.timeId);                if (fn) {     //回调函数
                    fn();
                }
            }
            console.log("当前位置:" + current + "目标位置:" + target + " 移动步数:" + step);   //测试函数
        }, 20);
    }    function getStyle(element, arrt) {
        return window.getComputedStyle ? window.getComputedStyle(element, null)[arrt] : element.currentStyle[arrt];

    }    function my$(id) {
        return document.getElementById(id);
    }    //写每张图片对应的样式
    var config = [
        {            &quot;width&quot;: 400,            &quot;top&quot;: 20,            &quot;left&quot;: 50,            &quot;opacity&quot;: 0.2,            &quot;zIndex&quot;: 2
        },      //0
        {            &quot;width&quot;: 600,            &quot;top&quot;: 70,            &quot;left&quot;: 0,            &quot;opacity&quot;: 0.8,            &quot;zIndex&quot;: 3
        },     //1
        {            &quot;width&quot;: 800,            &quot;top&quot;: 100,            &quot;left&quot;: 200,            &quot;opacity&quot;: 1,            &quot;zIndex&quot;: 4
        },     //2
        {            &quot;width&quot;: 600,            &quot;top&quot;: 70,            &quot;left&quot;: 600,            &quot;opacity&quot;: 0.8,            &quot;zIndex&quot;: 3
        },    //3
        {            &quot;width&quot;: 400,            &quot;top&quot;: 20,            &quot;left&quot;: 750,            &quot;opacity&quot;: 0.2,            &quot;zIndex&quot;: 2
        }    //4
    ];    var flag=true;     //假设动画全部执行完毕-----锁

    //页面加载的事件
    window.onload=function () {
        //1---散开图片
        var list=my$(&quot;slide&quot;).getElementsByTagName(&quot;li&quot;); //拿到所有li
        function assign() {    //分配函数
            for (var i=0;i&lt;list.length;i++){
                animate(list[i],config[i],function () {
                    flag=true;
                });
            }
        }
        assign();        //鼠标进入,左右焦点的p显示
        my$(&quot;wrap&quot;).onmouseover=function () {
            animate(my$(&quot;arrow&quot;),{&quot;opacity&quot;:1});
        };        //鼠标离开,左右焦点的p隐藏
        my$(&quot;wrap&quot;).onmouseout=function () {
            animate(my$(&quot;arrow&quot;),{&quot;opacity&quot;:0});
        };        //点击右边按钮事件
        my$(&quot;arrRight&quot;).onclick=function () {
            if (flag){
                flag=false;
                config.push(config.shift());     //把第一组值放到最后一组

                assign();
            }

        };        //点击左边按钮事件
        my$(&quot;arrLeft&quot;).onclick=function () {
            if (flag){
                flag=false;
                config.unshift(config.pop());   //把最后一组值放到第一组
                assign();
            }
        };
    };</script>
로그인 후 복사

관련 권장 사항:

이미지 압축을 위한 javascript 코드

도 및 도시 연결을 위한 javascript 코드 공유

위 내용은 기본 JS 캐러셀 렌더링의 애니메이션 효과(코드 포함)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!