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

时间:2015-06-14 20:05:53

标签: jquery rotation

我使用的是简单的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;
                    }
                }   
        }
        });
    });

当我点击文本旋转器中的链接时,它不会滚动,只是转到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);

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

1 个答案:

答案 0 :(得分:1)

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

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