Jquery水平滚动字幕(marquee效果)

水平滚动字幕

html:

<div class="txt-scroll">
    <div class="scrollbox">
        <div class="txt">div>
    div>
div>

css

.txt-scroll{ 
    width: 100%; 
    line-height: 1rem;
    height: 1rem;
    background-color: #CF2B18;
    color: #fff;
}
.txt-scroll .scrollbox{ 
    width: 100%; 
    white-space: nowrap; 
    overflow:hidden; 
    transition: all .2s; 
}
.txt-scroll .txt,
.txt-scroll .txt-clone{ 
    display: inline; 
    position: relative; 
}

封装的jquery插件(txtscroll):

;(function ($) {
    "use strict";
    $.fn.txtscroll = function (options) {
        //默认参数
        //{
        //   speed - 滚动间隔时间
        //}
        
        var settings = $.extend({
            'speed': 50
        }, options);

        return this.each(function () {
            var $this = $(this);
            var $settings = settings;

            var scrollbox = $('.scrollbox',$this);
            var txt_begin = $('.txt',$this);
            var txt_end = $('
'
); var scrollVaue = 0; function marquee() { if (txt_end.width() - scrollbox.scrollLeft() <= 0){ scrollVaue = scrollbox.scrollLeft() - txt_begin.width(); scrollbox.scrollLeft(scrollVaue); } else{ scrollVaue = scrollVaue + 1; scrollbox.scrollLeft(scrollVaue); } } if(txt_begin.width() > scrollbox.width()){ txt_end.html(txt_begin.html()); scrollbox.append(txt_end); //点击滚动条停止滚动效果(建议去掉) //var setmarquee = setInterval(marquee, $settings.speed); // $this.on('mouseover', function(){ // clearInterval(setmarquee); // }); // $this.on('mouseout', function(){ // setmarquee = setInterval(marquee, $settings.speed); // }); } }); }; })(jQuery);

js中使用:

$.ajax({ 
    url: url, 
    type: "get",
    success: function(res){
             res = JSON.parse(res);
             if(res.code == 200){
                if(res.data){
                 var news=
                 res.data.join('      ');
                 //每条数据间留空隙   
                 $(".txt").html('      '+news);
                 //第一条留空隙
                 $('.txt-scroll').txtscroll({'speed': 50});
                 //控制滚动速度
                    }
                }
            },
            error:function(){
            }
        }); 

效果:
在这里插入图片描述

你可能感兴趣的:(Jquery水平滚动字幕(marquee效果))