CSS/JQuery powered sideways scrolling text on hover

后端 未结 6 1399
醉话见心
醉话见心 2021-02-06 04:03

I have a twitter feed on a website I run. However, it gets cut off on small screens. I have a bar tall enough for 1 line of text in which I have the latest tweet. I want the twe

6条回答
  •  借酒劲吻你
    2021-02-06 04:55

    Here's a fairly simple way to do it. First, set up a div containing your long text:

    Here is the long content, long long content. So long. Too long.

    You can use some css to automatically handle the truncation and ellipsis:

    div#container {
        /* among other settings: see fiddle */
        width: 200px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
    }
    

    If you then determine the native, untruncated width of the content, you can use jQuery's .animate() to move that content at a consistent speed -- even if you don't know the length of the text until runtime (as would be the case with a twitter feed). Here's a somewhat mechanical way of getting the measurement:

    var true_width = ( function(){
      var $tempobj = $('#container') // starting with truncated text div container
          .clone().contents() // duplicate the text
          .wrap('
    ') // wrap it in a container .parent().appendTo('body') // add this to the dom .css('left','-1000px'); // but put it far off-screen var result = $tempobj.width(); // measure it $tempobj.remove(); // clean up return result; })();

    Finally, some animation:

    $('#container').one('mouseenter', function(){ // perhaps trigger once only
      var shift_distance = true_width - $(this).width(); // how far to move
      var time_normalized = parseInt(shift_distance / 100, 10) * 1000; // speed
      $(this).contents().wrap('
    ').parent() // wrap in div .animate({ left: -shift_distance, right: 0 }, time_normalized, 'linear'); // and move the div within its "viewport" });

    Regardless of the length of the text, you'll get a consistent speed of about one second per 100 pixels (adjust as desired). Resetting or rewinding content on mouseleave is left as an exercise. This approach has some naïve bits, but may give you some ideas.

    Here's a working example: http://jsfiddle.net/redler/zdvyj/

提交回复
热议问题