jQuery + css announcement scroll left to right

<!DOCTYPE html>
<html>
<head>
    <title>demo</title>
    <style type="text/css">
        
 
        .notice-content {
            position: relative;
            width: 800px;
            height: 30px;
            white-space: nowrap;
            overflow: hidden;
            float: left;
            display: inline-block;
            /*margin-left: 55px;*/
            /*margin-top: -30px;       */
        }
        .notice-text {
            display: inline-block;
            color: red;
            font-size: 14px;
            position: absolute;
            width: 100%;
            height: 100%;
            cursor: pointer;
        }
    </style>
</head>
<body>
<span class="notice-content">
    <span class="notice-text">
        Announcement content
    </span>
</span>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
    // Notice scroll 
    $( " .notice-content " ).textScroll();
});
 
/**
 * scroll text from right to left
 * @returns {undefined}
 */ 
$.fn.textScroll = function() {
     // Scroll step size (the larger the step size, the faster the speed) 
    var step_len = 60 ;
     var this_obj = $( this );
     var child = this_obj.children();
     var this_width = this_obj.width();
     var child_width = child.width();
     var continue_speed = undefined; // Resume animation speed after pause
     // initial text position 
    child.css({
        left: this_width
    });
 
    // Initial animation speed speed 
    var init_speed = (child_width + this_width) / step_len * 1000 ;
 
    // 滚动动画
    function scroll_run(continue_speed) {
        var speed = (continue_speed == undefined ? init_speed : continue_speed);
        child.animate({
            left: -child_width
        }, speed, "linear", function() {
            $(this).css({
                left: this_width
            });
            scroll_run();
        });
    }
 
    // Mouse action 
    child.on({
        mouseenter: function() {
            var current_left = $(this).position().left;
            $(this).stop();
            continue_speed = (-(-child_width - current_left) / step_len) * 1000;
        },
        mouseleave: function() {
            scroll_run(continue_speed);
            continue_speed = undefined;
        }
    });
 
    // Start scrolling 
    scroll_run();
};
</script>
</body>
</html>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325161155&siteId=291194637