jQuery - 带有点击事件的简单文本旋转器

jQuery - Simple Text Rotator with click event

我正在使用 Simple Text Rotator,它很棒,我唯一遇到的问题是我无法使用它的点击事件:

$(function() {
        $('a[href*=#]:not([href=#])').click(function() {
        if(!$(this).hasClass('carousel-control')){
                if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                    var target = $(this.hash);
                    target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                    if (target.length) {
                            $('html,body').animate({
                                scrollTop: target.offset().top - topSize
                            }, 2000);
                            return false;
                    }
                }   
        }
        });
    });

当我在文本旋转器中单击 link 时,它不会滚动,只会转到 ID 部分(#link-1 和 #link-2)( link-3.php 和 link-4.php 工作正常,因为它们会转到另一个页面)

 <h1 class="sliding-text">
        <span class="rotate">
            <a href="#link-1">Link 1</a>, 
            <a href="#link-2">Link 2</a>,
            <a href="link-3.php">Link 3</a>,
            <a href="link-4.php">Link 4</a>
        </span>
    </h1>

    $(".sliding-text .rotate").textrotator({
        animation: "fade",
        speed: 1000
    });

这里是库的 jquery 代码:

!function ($) {

    var defaults = {
        animation: "fade",
        separator: ",",
        speed: 2000
    };

    $.fx.step.textShadowBlur = function (fx) {
        $(fx.elem).prop('textShadowBlur', fx.now).css({ textShadow: '0 0 ' + Math.floor(fx.now) + 'px black' });
    };

    $.fn.textrotator = function (options) {
        var settings = $.extend({}, defaults, options);

        return this.each(function () {
            var el = $(this)
            var array = [];
            $.each(el.html().split(settings.separator), function (key, value) {
                array.push(value);
            });
            el.html(array[0]);

            // animation option
            var rotate = function () {
                switch (settings.animation) {

                    case 'fade':
                        el.fadeOut(500, function () {
                            index = $.inArray(el.html(), array)
                            if ((index + 1) == array.length) index = -1
                            el.text(array[index + 1]).fadeIn(settings.speed);
                        });
                        break;
                }
            };
            setInterval(rotate, 8000);
        });
    }

}(window.jQuery);

如何让我的点击事件与我的文本旋转器一起工作

我认为它不起作用,因为文本旋转器插件正在删除并重新添加 DOM 中的链接。您可以使用 delegated event binding 解决此问题,如下所示:

$(function() {
  $('.sliding-text').on('click', 'a[href*=#]:not([href=#])', function() {
    // .. your code here
  });
});