删除简单文本轮换的jQuery依赖

时间:2018-01-19 17:04:37

标签: javascript jquery

目前我正在为一个非常简单的东西加载一个完整的jQuery库。它通过跨度列表来关联,每个跨度包含不同的文本,因此每次消息都不同。

以下是我的代码:



(function($){
    $.fn.extend({ 
        rotaterator: function(options) {

            var defaults = {
                fadeSpeed: 500,
                pauseSpeed: 500,
                child:null
            };

            var options = $.extend(defaults, options);

            return this.each(function() {
                  var o =options;
                  var obj = $(this);                
                  var items = $(obj.children(), obj);
                  items.each(function() {$(this).hide();})
                  if(!o.child){var next = $(obj).children(':first');
                  }else{var next = o.child;
                  }
                  $(next).fadeIn(o.fadeSpeed, function() {
                        $(next).delay(o.pauseSpeed).fadeOut(o.fadeSpeed, function() {
                            var next = $(this).next();
                            if (next.length == 0){
                                    next = $(obj).children(':first');
                            }
                            $(obj).rotaterator({child : next, fadeSpeed : o.fadeSpeed, pauseSpeed : o.pauseSpeed});
                        })
                    });
            });
        }
    });
})(jQuery);

 $(document).ready(function() {
        $('.rotate').rotaterator({fadeSpeed:500, pauseSpeed:6000});
 });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2 class="light content-medium center text-center soft-top--quad">
Join us for a
    <div class="rotate"> 
        <span>relaxed</span>
        <span>wonderful</span>
      	<span>crazy</span>
    </div> 
  weekend of
  <div class="rotate"> 
        <span>fun</span>
        <span>games</span>
        <span>laughter</span>
      	<span>dancing</span>
    	<span>love</span>
  </div> resulting in your
  <div class="rotate"> 
        <span>best</span>
        <span>worst</span>
        <span>most disgusting</span>
    </div>
     <div class="rotate"> 
        <span>memories</span>
        <span>hangover</span>
    </div>
		    </h2>
&#13;
&#13;
&#13;

我希望用香草JavaScript重新实现这一点,并想知道这是否是一件容易的工作?例如,这里有什么东西在很大程度上依赖于jQuery吗?

我怎样才能最好地开始这个,因为我对JavaScript很陌生?

1 个答案:

答案 0 :(得分:2)

实际上你需要一个完整的重写。 我看了一眼并从头开始编写了一个具有相同功能的香草剧本,而没有关心以前的逻辑。 我使用CSS转换而不是任何JavaScript动画库。

由于这是一个快速的镜头,没有人付钱给我,它不是最好和最有效的代码,它可以使用更多的功能和回调进行改进。

有几个setTimeout和多个DOM更新 我们还必须关注其他项目应该被隐藏的事实(使用display: none以便它们不使用空间)但我们不能通过同时设置display: inline; opacity: 1淡入已隐藏的项目那一刻,否则我们就不会看到过渡。

在ES2015 + 中可以做得更好更少的行,箭头功能和Promise,但是因为我不知道你需要这个脚本的位置以及你想要的浏览器为了支持,我在丑陋的旧平原ES5中写道。

/**
 * The new fancy VanillaJS rotaterator
 * @param {string} selector 
 * @param {object} options 
 */
function rotaterator(selector, options) {
    var defaults = {
        fadeSpeed: 500,
        pauseSpeed: 500,
        child: null
    };

    var options = Object.assign(defaults, options);
    var items = document.querySelectorAll(selector);
    var allSpans = [];

    /**
     * Fade all elements of the given array in by setting display and opacity
     * @param {array} arrElements 
     */
    function fadeElementsIn(arrElements) {
        arrElements.forEach(function (e) {
            if (e.style.display === 'none') {
                // if we are setting from none directly to inline, we need a small delay
                e.style.display = 'inline';
                window.setTimeout(function () {
                    e.style.opacity = 1;
                }, 10);
            } else
                e.style.opacity = 1;
        });
    }

    /**
     * Hide all previously cached span elements by setting display to none
     */
    function hideAll() {
        allSpans.forEach(function (e) {
            e.style.display = 'none';
        });
    }

    /**
     * Set initial styles and transition and fade first elements in
     */
    function initialize(onInitialized) {
        var initialFadeIn = [];
        items.forEach(function (item) {
            var spans = item.querySelectorAll('span');
            spans.forEach(function (span) {
                allSpans.push(span);
                span.style.opacity = 0;
                span.style.transition = (options.fadeSpeed / 1000) + 's linear';
            });

            initialFadeIn.push(spans[0]);
        });

        // finally fade the first set of elements in and call the callback
        window.setTimeout(function () {
            fadeElementsIn(initialFadeIn);
            onInitialized();
        }, 10);
    }

    /**
     * Fade the current items out and fade the next items in
     */
    function next() {
        window.setTimeout(function () {
            var toFadeIn = [];

            items.forEach(function (item) {
                var nextIndex;
                for (var i = 0; i < item.children.length; i++) {
                    if (item.children[i].style.opacity == 1) {
                        // fade current item out
                        item.children[i].style.opacity = 0;

                        // set next index to fadeIn
                        nextIndex = (i + 1 > item.children.length - 1 ? 0 : i + 1);
                    }
                }

                // save the next element to array
                toFadeIn.push(item.children[nextIndex]);
            });

            // wait for fade out transition effect to complete and then fade all new elements in
            window.setTimeout(function () {
                hideAll();
                fadeElementsIn(toFadeIn);

                // after fadeIn transition effect call this method recursive.
                window.setTimeout(function () {
                    next();
                }, options.fadeSpeed);
            }, options.fadeSpeed);
        }, options.pauseSpeed);
    }

    initialize(next);
}

ready(function () {
    rotaterator('.rotate', { fadeSpeed: 500, pauseSpeed: 6000 });
});

/**
 * Polyfill for Object.assign
 */
if (typeof Object.assign != 'function') {
    Object.assign = function (target) {
        'use strict';
        if (target == null) {
            throw new TypeError('Cannot convert undefined or null to object');
        }

        target = Object(target);
        for (var index = 1; index < arguments.length; index++) {
            var source = arguments[index];
            if (source != null) {
                for (var key in source) {
                    if (Object.prototype.hasOwnProperty.call(source, key)) {
                        target[key] = source[key];
                    }
                }
            }
        }
        return target;
    };
}

/**
 * document.ready function without jQuery
 * @param {function} fn 
 */
function ready(fn) {
    if (document.attachEvent ? document.readyState === "complete" : document.readyState !== "loading") {
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}