简体   繁体   中英

Random Text On MouseOver And On MouseLeave Show The Real Text

我想要一个javascript函数,如果我将鼠标悬停在像“ExampleText”这样的文本上,它将生成一些具有相同长度的悬停文本的随机字符,如“$ 45a%b8r5c7”,并且每次生成随机字符。如果我在文本上取消悬停它会显示旧的orignal文本,即“ExampleText”。

Try this

$('body').on('mouseenter', '.change', function(){
    $('.change').html(Math.random().toString(36).substring(7));
}).on('mouseleave', function(){
    $('.change').html('Example');
});

<div class="change">Example</div>

If you want to specify the generated characters, maybe you can use something like this:

https://jsfiddle.net/uk7xyapa/1/

Html:

<span id="originalText">ExampleText</span>
<span id="newText">ExampleText</span>

jQuery:

$(document).ready(function(){
    var originalText = $( "#originalText" ).text();
    $( "#originalText" ).mouseenter(function() {
        var text = '';
        var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789%$';

        for(var i=0; i < $( "#originalText" ).text().length; i++)
        {
            text += possible.charAt(Math.floor(Math.random() * possible.length));
        }
        $( "#newText" ).text( text );
    });
    $( "#originalText" ).mouseleave(function() {
        $( "#newText" ).text( originalText );
    });
})

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