2

我有一个用于歌曲标题的块元素(一个绝对定位的 h1,具有最大宽度、nowrap 和溢出:隐藏),需要限制为 650 像素宽。如果 H1 的宽度为 650 像素,我需要启动一个动画,以类似乒乓球的方式水平、前后滚动 div。

我将如何为滚动制作动画?

4

3 回答 3

2

我知道这不是解决这个问题的最有效或最好的方法,但我最终创建了两个 jquery 函数来完成任务:

$.fn.pingpongscroll = function () {
    var delay = 30;
    $(this).wrapInner('<span>');
    var contentWidth = $(this).children('span').width();
    var boxWidth = $(this).width();

    if (contentWidth > boxWidth) {
        var startIndent = parseInt($(this).css('text-indent'));
        var currIndent  = startIndent;
        var left = true;
        $(this).pingpongscrollstep(contentWidth, startIndent, currIndent, left, delay);
    }
};
$.fn.pingpongscrollstep = function (contentWidth, startIndent, currIndent, left, delay) {
    if($(this).length != 0) {
        thisdelay = delay;
        if(left) {
            if(contentWidth + currIndent > $(this).width()) {
                currIndent = currIndent - 1;
                $(this).css('text-indent', currIndent);
            } else {
                left = false;
                thisdelay = thisdelay*20;
            }
        } else {
            if(currIndent < startIndent) {
                currIndent = currIndent + 1;
                $(this).css('text-indent', currIndent);
            } else {
                left = true;
                thisdelay = thisdelay*30;
            }
        }
        var thiselement = this;
        setTimeout(function(){
            $(thiselement).pingpongscrollstep(contentWidth, startIndent, currIndent, left, delay);
        }, thisdelay);
    }
};

虽然这些工作得很好,但我确信这不是处理滚动的正常方式。另外,我不知道如何使第二个函数成为第一个函数的私有成员,因此该站点不能调用它...有人知道该怎么做吗?

于 2013-07-31T19:38:57.720 回答
0

我重构了Greg Schoppe 提供的代码以使用 jQuery 动画子系统。

我的版本和他的版本之间的时间有点不同,但这应该很容易调整。

(function( $ ) {
    $.fn.pingpongscroll = function () {
        $(this).wrapInner('<span style="white-space: nowrap">');
        var contentWidth = $(this).children('span').width();
        var boxWidth = $(this).width();

        if (contentWidth > boxWidth) {
            var startIndent = parseInt($(this).css('text-indent'));
            var currIndent  = startIndent;
            var left = true;

            var maxIndent = $(this).width() - contentWidth;
            pingpong($(this));

            function pingpong($el) {
                $el
                    .delay(2500)
                    .animate(
                        {'text-indent' : maxIndent},
                        5000,
                        'linear')
                    .delay(2500)
                    .animate(
                        {'text-indent' : startIndent},
                        5000,
                        'linear',
                        function() {
                            pingpong($el)
                        });
            }
        }
    };
})(jQuery);
于 2015-04-14T21:08:15.593 回答
0

有一个 jquery marquee 插件

http://plugins.jquery.com/marquee/

于 2013-07-31T17:22:12.177 回答