非常简单,非常流畅的JavaScript跑马灯

32

我正在寻找一个非常简单、流畅、轻量级的JavaScript或jQuery跑马灯。我已经尝试过silk marquee或其他一些东西,但它不能在我的应用程序中使用。所以越简单、越短,越好——也更容易调试。有人知道一个易于实现的JavaScript替代跑马灯吗?

Pastebin

代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
var tWidth='300px';                  // width (in pixels)
var tHeight='25px';                  // height (in pixels)
var tcolour='#ffffcc';               // background colour:
var moStop=true;                     // pause on mouseover (true or false)
var fontfamily = 'arial,sans-serif'; // font for content
var tSpeed=3;                        // scroll speed (1 = slow, 5 = fast)

// enter your ticker content here (use \/ and \' in place of / and ' respectively)
var content='Are you looking for loads of useful information <a href="http:\/\/javascript.about.com\/">About Javascript<\/a>? Well now you\'ve found it.';

var cps=-tSpeed; var aw, mq; var fsz = parseInt(tHeight) - 4; function startticker(){if (document.getElementById) {var tick = '<div style="position:relative;width:'+tWidth+';height:'+tHeight+';overflow:hidden;background-color:'+tcolour+'"'; if (moStop) tick += ' onmouseover="cps=0" onmouseout="cps=-tSpeed"'; tick +='><div id="mq" style="position:absolute;right:0px;top:0px;font-family:'+fontfamily+';font-size:'+fsz+'px;white-space:nowrap;"><\/div><\/div>'; document.getElementById('ticker').innerHTML = tick; mq = document.getElementById("mq"); mq.style.right=(10+parseInt(tWidth))+"px"; mq.innerHTML='<span id="tx">'+content+'<\/span>'; aw = document.getElementById("tx").offsetWidth; lefttime=setInterval("scrollticker()",50);}} function scrollticker(){mq.style.right = (parseInt(mq.style.right)>(-10 - aw)) ?
mq.style.right = parseInt(mq.style.right)+cps+"px": parseInt(tWidth)+10+"px";} window.onload=startticker;
</script>
</head>
<body>
<div id="ticker">
    this is a simple scrolling text!
</div>
</body>
</html>

2
“wouldn't work”这个描述几乎没有任何意义,请具体描述它为什么无法工作?同时请提供您的标记代码。 - Andreas Wong
4
嗨呀,写一些代码吧,这样可以帮助我们更好地帮助你。无论如何,希望这能帮到你。这是链接:http://jsfiddle.net/FWWEn/。祝你愉快,再见! - Tats_innit
我已经玩了几个小时,删除了丝绸马克纪,并转向了另外几个没有成功的马克纪。问题是我正在尝试将其实现到Joomla中,这就是为什么越简单越好的原因。我只是在寻找更多选项 :/ - Derp
1
@Tats_innit:为什么你不把它作为答案加进去呢?代码写得很不错。 - jgauffin
1
@Derp 这不是认真的;) 那段代码看起来非常好。 - Christoph
显示剩余4条评论
10个回答

46

嗨呀,这是上面评论中推荐的一个简单示例http://jsfiddle.net/FWWEn/

带有鼠标悬停暂停功能的示例:http://jsfiddle.net/zrW5q/

希望对您有所帮助,祝您过得愉快,干杯!

HTML

<h1>Hello World!</h1>
<h2>I'll marquee twice</h2>
<h3>I go fast!</h3>
<h4>Left to right</h4>
<h5>I'll defer that question</h5>

Jquery代码

 (function($) {
        $.fn.textWidth = function(){
             var calc = '<span style="display:none">' + $(this).text() + '</span>';
             $('body').append(calc);
             var width = $('body').find('span:last').width();
             $('body').find('span:last').remove();
            return width;
        };

        $.fn.marquee = function(args) {
            var that = $(this);
            var textWidth = that.textWidth(),
                offset = that.width(),
                width = offset,
                css = {
                    'text-indent' : that.css('text-indent'),
                    'overflow' : that.css('overflow'),
                    'white-space' : that.css('white-space')
                },
                marqueeCss = {
                    'text-indent' : width,
                    'overflow' : 'hidden',
                    'white-space' : 'nowrap'
                },
                args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args),
                i = 0,
                stop = textWidth*-1,
                dfd = $.Deferred();

            function go() {
                if(!that.length) return dfd.reject();
                if(width == stop) {
                    i++;
                    if(i == args.count) {
                        that.css(css);
                        return dfd.resolve();
                    }
                    if(args.leftToRight) {
                        width = textWidth*-1;
                    } else {
                        width = offset;
                    }
                }
                that.css('text-indent', width + 'px');
                if(args.leftToRight) {
                    width++;
                } else {
                    width--;
                }
                setTimeout(go, args.speed);
            };
            if(args.leftToRight) {
                width = textWidth*-1;
                width++;
                stop = offset;
            } else {
                width--;            
            }
            that.css(marqueeCss);
            go();
            return dfd.promise();
        };
    })(jQuery);

$('h1').marquee();
$('h2').marquee({ count: 2 });
$('h3').marquee({ speed: 5 });
$('h4').marquee({ leftToRight: true });
$('h5').marquee({ count: 1, speed: 2 }).done(function() { $('h5').css('color', '#f00'); })​

这很奇怪,我将完全相同的HTML文档复制到JSFiddle中,它可以完美运行,但是在本地或服务器上却什么都没有。我知道我的jQuery链接正确,也许是我的文档类型有问题。我正在尝试不同的选项。谢谢。 - Derp
在我的Firefox中,这绝不是“非常流畅”... 唉...当然不是你的错;它是数十层抽象的结果,燃烧了数百万个CPU周期只为了移动一些文本... - Roman Starkov
@romkyns :) 我正在寻找微软的官方文档 #如果有的话,以了解 marquee 标签背后的思想,因为它始终是非标准的 HTML 标签 - 如果你找到了,请告诉我 :)) 虽然感谢您的评论,但我们下次再见吧。 - Tats_innit
4
这个实现是否允许大量文本的环绕显示? 我所找到/尝试过的所有方法似乎都是等待文本移出屏幕并重新开始,而不是无缝地滚动。 - Maslow
这可能是一个好的实现方式,但现在已经过时了。 - Howdy_McGee
显示剩余8条评论

14

我为跑马灯制作了非常简单的函数。请看:http://jsfiddle.net/vivekw/pHNpk/2/。它可以在鼠标悬停时暂停,并在鼠标离开时恢复。速度可以变化。易于理解。

function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;

function scroll() {
    if (b.position().left <= -width) {
        b.css('left', start_pos);
        scroll();
    }
    else {
        time = (parseInt(b.position().left, 10) - end_pos) *
            (10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
        b.animate({
            'left': -width
        }, time, 'linear', function() {
            scroll();
        });
    }
}

b.css({
    'width': width,
    'left': start_pos
});
scroll(a, b);
b.mouseenter(function() {     // Remove these lines
    b.stop();                 //
    b.clearQueue();           // if you don't want
});                           //
b.mouseleave(function() {     // marquee to pause
    scroll(a, b);             //
});                           // on mouse over
}

$(document).ready(function() {
    marquee($('#display'), $('#text'));  //Enter name of container element & marquee element
});

如果你为参数命名,那么它将更易于理解。 - OG Sean

11

1
链接是有效的。然而,该脚本非常卡顿。我建议使用 丝滑平滑的跑马灯 - Onimusha
请按照http://aamirafridi.com/jquery/jquery-marquee-plugin上显示的说明进行操作。您没有将CSS应用于跑马灯元素。 - Aamir Afridi
1
@Onimusha插件现在支持CSS3,并且更加流畅。 - Aamir Afridi
@AamirAfridi 由于rawgithub链接无法使用,我将jquery.marquee.min.js集成到页脚的脚本末尾,它一直在工作,但现在出了一些问题。看起来周围的div已经添加了,但是跑马灯没有移动。这是输出的pastebin:http://pastebin.com/KCH76pY2。你能帮我解决这个问题吗?现场网址是keebs.com/sandbox。顶部的最新推文应该是跑马灯效果。 - J82
@AamirAfridi 我刚刚发现它在Firefox中能够工作,但是在Chrome、Safari或IE中无法工作。而且,我没有安装任何浏览器扩展也测试了一下。 - J82
显示剩余5条评论

7
以下内容正常运行: http://jsfiddle.net/xAGRJ/4/ 原始代码的问题在于您通过将字符串传递给setInterval来调用scrollticker(),而您应该只传递函数名称并将其视为变量:
lefttime = setInterval(scrollticker, 50);

替换为
lefttime = setInterval("scrollticker()", 50);

@Derp兄弟,如果那个解决了你的问题,请至少接受他的答案:)这只是一个观察,放轻松:),干杯! - Tats_innit
我修复了一个问题,但导致了另一个问题,可能是因为tSpeed未定义,出现在这里 - onmouseout="cps=-tSpeed"。不过我正在尝试解决它。 - Derp
这将影响变量的范围,将其作为字符串传递将使用不同的范围,该范围可以访问使用函数变量引用范围无法访问的变量。一些重构可能会修复它,但通常需要重写,而字符串版本可能可以正常工作。仍然我想知道requestAnimationFrame或jquery animate是否比在timeout-set帧率上循环增加更平滑...任何timeout迭代动画帧都似乎存在平滑性问题。 - OG Sean

7

为什么要编写自定义的jQuery代码来实现滚动效果,只需要使用一个jQuery插件-marquee()并像下面的示例一样使用它:

首先包含:

<script type='text/javascript' src='//cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js'></script>

并且:
//proporcional speed counter (for responsive/fluid use)
var widths = $('.marquee').width()
var duration = widths * 7;

$('.marquee').marquee({
    //speed in milliseconds of the marquee
    duration: duration, // for responsive/fluid use
    //duration: 8000, // for fixed container
    //gap in pixels between the tickers
    gap: $('.marquee').width(),
    //time in milliseconds before the marquee will start animating
    delayBeforeStart: 0,
    //'left' or 'right'
    direction: 'left',
    //true or false - should the marquee be duplicated to show an effect of continues flow
    duplicated: true
});

如果你能简化和改进它,我敢挑战所有人 :). 不要把生活变得比必须复杂。有关此插件及其功能的更多信息,请访问:http://aamirafridi.com/jquery/jquery-marquee-plugin

这似乎在IE 10及更高版本上无法正常工作。非常奇怪。也许有人可以指出一些修复或解决方法?我被迫使用jQuery 1.5.1。 - Tornike Shavishvili

2

我基于@Tats_innit上面所提供的代码制作了自己的版本。唯一的不同在于暂停功能。在这方面运转得更好一些。

(function ($) {
var timeVar, width=0;

$.fn.textWidth = function () {
    var calc = '<span style="display:none">' + $(this).text() + '</span>';
    $('body').append(calc);
    var width = $('body').find('span:last').width();
    $('body').find('span:last').remove();
    return width;
};

$.fn.marquee = function (args) {
    var that = $(this);
    if (width == 0) { width = that.width(); };
    var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
        css = {
            'text-indent': that.css('text-indent'),
            'overflow': that.css('overflow'),
            'white-space': that.css('white-space')
        },
        marqueeCss = {
            'text-indent': width,
            'overflow': 'hidden',
            'white-space': 'nowrap'
        },
        args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);

    function go() {
        if (!that.length) return dfd.reject();
        if (width <= stop) {
            i++;
            if (i <= args.count) {
                that.css(css);
                return dfd.resolve();
            }
            if (args.leftToRight) {
                width = textWidth * -1;
            } else {
                width = offset;
            }
        }
        that.css('text-indent', width + 'px');
        if (args.leftToRight) {
            width++;
        } else {
            width=width-2;
        }
        if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
        if (args.pause == true) { clearTimeout(timeVar); };
    };

    if (args.leftToRight) {
        width = textWidth * -1;
        width++;
        stop = offset;
    } else {
        width--;
    }
    that.css(marqueeCss);

    timeVar = setTimeout(function () { go() }, 100);

    return dfd.promise();
};
})(jQuery);

用法:

开始滚动:$('#Text1').marquee()

暂停滚动:$('#Text1').marquee({ pause: true })

恢复滚动:$('#Text1').marquee({ pause: false })


注:此为it技术相关内容,涉及jquery插件使用方法。

1

我的文本跑马灯可以显示更多文本,并启用绝对定位

http://jsfiddle.net/zrW5q/2075/

(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
  position: 'absolute',
  visibility: 'hidden',
  height: 'auto',
  width: 'auto',
  'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};

$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
    offset = that.width(),
    width = offset,
    css = {
        'text-indent': that.css('text-indent'),
        'overflow': that.css('overflow'),
        'white-space': that.css('white-space')
    },
    marqueeCss = {
        'text-indent': width,
        'overflow': 'hidden',
        'white-space': 'nowrap'
    },
    args = $.extend(true, {
        count: -1,
        speed: 1e1,
        leftToRight: false
    }, args),
    i = 0,
    stop = textWidth * -1,
    dfd = $.Deferred();

function go() {
    if (that.css('overflow') != "hidden") {
        that.css('text-indent', width + 'px');
        return false;
    }
    if (!that.length) return dfd.reject();

    if (width <= stop) {
        i++;
        if (i == args.count) {
            that.css(css);
            return dfd.resolve();
        }
        if (args.leftToRight) {
            width = textWidth * -1;
        } else {
            width = offset;
        }
    }
    that.css('text-indent', width + 'px');
    if (args.leftToRight) {
        width++;
    } else {
        width--;
    }
    setTimeout(go, args.speed);
};

if (args.leftToRight) {
    width = textWidth * -1;
    width++;
    stop = offset;
} else {
    width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {     
    $(this).removeAttr("style");
}).mouseout(function () {
    $(this).marquee();
});
})(jQuery);

1

响应式的纯jQuery滚动插件。教程:

// start plugin
    (function($){
        $.fn.marque = function(options, callback){

            // check callback

            if(typeof callback == 'function'){
                callback.call(this);
            } else{
                console.log("second argument (callback) is not a function");
                // throw "callback must be a function"; //only if callback for some reason is required
                // return this; //only if callback for some reason is required
            }

            //set and overwrite default functions
            var defOptions = $.extend({
                speedPixelsInOneSecound: 150, //speed will behave same for different screen where duration will be different for each size of the screen
                select: $('.message div'),
                clickSelect: '', // selector that on click will redirect user ... (optional)
                clickUrl: '' //... to this url. (optional)
            }, options);

            //Run marque plugin
            var windowWidth = $(window).width();
            var textWidth = defOptions.select.outerWidth();
            var duration = (windowWidth + textWidth) * 1000 / defOptions.speedPixelsInOneSecound;
            var startingPosition = (windowWidth + textWidth);
            var curentPosition = (windowWidth + textWidth);
            var speedProportionToLocation = curentPosition / startingPosition;
            defOptions.select.css({'right': -(textWidth)});
            defOptions.select.show();
            var animation;


            function marquee(animation){
                curentPosition = (windowWidth + defOptions.select.outerWidth());
                speedProportionToLocation = curentPosition / startingPosition;
                animation = defOptions.select.animate({'right': windowWidth+'px'}, duration * speedProportionToLocation, "linear", function(){
                     defOptions.select.css({'right': -(textWidth)});
                });
            }
            var play = setInterval(marquee, 200);

            //add onclick behaviour
            if(defOptions.clickSelect != '' && defOptions.clickUrl != ''){
                defOptions.clickSelect.click(function(){
                    window.location.href = defOptions.clickUrl;
                });
            }
            return this;
        };

    }(jQuery)); 
// end plugin 

使用以下自定义 jQuery 插件:
//use example
$(window).marque({
    speedPixelsInOneSecound: 150, // spped pixels/secound
    select: $('.message div'), // select an object on which you want to apply marquee effects.
    clickSelect: $('.message'), // select clicable object (optional)
    clickUrl: 'services.php' // define redirection url (optional)
});

0

使用CSS动画来制作跑马灯效果。

`<style>
.items-holder {
animation: moveSlideshow 5s linear infinite;
}

.items-holder:hover {
animation-play-state: paused;
}

@keyframes moveSlideshow {
100% { 
transform: translateX(100%);  
}
}
</style>`

1
你的回答可以通过提供更多支持信息来改进。请编辑以添加进一步的细节,例如引用或文档,以便他人可以确认你的答案是正确的。您可以在帮助中心找到有关如何编写良好答案的更多信息。 - Community

0

我尝试仅使用css来处理此链接

<style>
    .header {
        background: #212121;
        overflow: hidden;
        height: 65px;
        position: relative;
    }
    .header div {
        display: flex;
        flex-direction: row;
        align-items: center;
        overflow: hidden;
        height: 65px;
        transform: translate(100%, 0);
    }
    .header div * {
        font-family: "Roboto", sans-serif;
        color: #fff339;
        text-transform: uppercase;
        text-decoration: none;
    }
    .header div img {
        height: 60px;
        margin-right: 20px;
    }
    .header .ticker-wrapper__container{
        display: flex;
        flex-direction: row;
        align-items: center;
        position: absolute;
        top: 0;
        right: 0;
        animation: ticker 30s infinite linear forwards;
    }

    .header:hover .ticker-wrapper__container{
        animation-play-state: paused;
    }

    .ticker-wrapper__container a{
        display: flex;
        margin-right: 60px;
        align-items: center;
    }

    @keyframes ticker {
        0% {
            transform: translate(100%, 0);
        }
        50% {
            transform: translate(0, 0);
        }
        100% {
            transform: translate(-100%, 0);
        }
    }
</style>       

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接