简体   繁体   中英

Using jQuery to Insert Text in Span on Hover and Slide from Left to Right

<p class="site-description">Its fun to <span class="description-addition"></span>eat cookies</p>

<script>
    var quotes = new Array('do whatever and ', 'live life and ', 'get funky and ', 'do your thing and ');
    $('.site-description').mouseover(function() {
        $('.description-addition').text(quotes[Math.floor ( Math.random() * quotes.length )]);
    }).mouseout(function() {
        $('.description-addition').text("");
    });
</script

The basic idea here is to add a random phrase from the quotes array in the description-addition span. This works perfectly, but I'm having trouble animating it. I've tried using .animate() and .toggle() to no avail. I'd like the text to slide out from left to right and have width of the span expand accordingly. The text always mis-aligned one way or another. Any help would be appreciated!

Demo: Codepen

<p class="site-description">Its fun to <span class="description-addition" style="display:none;"></span> eat cookies</p>

Added the animation after setting the next text/string and set a display:none; in your span.

$(document).ready(function() {
    var quotes = new Array('do whatever and ', 'live life and ', 'get funky and ', 'do your thing and ');

    $('.site-description').mouseover(function() {
        $('.description-addition').text(quotes[Math.floor ( Math.random() * quotes.length )]+' ').toggle("slow");
    }).mouseout(function() {
        $('.description-addition').toggle("fast");
    });
});

Hope this is what you were after. CodePen Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM