使用javascript或jquery的随机单词弹出脚本

Random word popup script using javascript or jquery

本文关键字:单词弹 脚本 随机 javascript jquery 使用      更新时间:2023-09-26

所以我已经在这里找到了它,它几乎正是我想要的。唯一的区别是,我不想创建方框,而是希望它们是从数组中提取的单词,就像一样

var textarray = [
    "wow",
    "so amaze",
    "much hunt",
    "such treasure"];

因此,它将是一个随机着色的单词,而不是随机弹出的彩色框。这是jsfiddle的代码。

(function makeDiv(){
    var divsize = ((Math.random()*100) + 50).toFixed();
    var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
    $newdiv = $('<div/>').css({
        'width':divsize+'px',
        'height':divsize+'px',
        'background-color': color
    });
    var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
    var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
    $newdiv.css({
        'position':'absolute',
        'left':posx+'px',
        'top':posy+'px',
        'display':'none'
    }).appendTo( 'body' ).fadeIn(100).delay(300).fadeOut(200, function(){
       $(this).remove();
       makeDiv(); 
    }); 
})();

这是怎么回事?http://jsfiddle.net/x2EXz/1/(对以下所列变更的评论)

var textArray = [
    "wow",
    "so amaze",
    "much hunt",
    "such treasure"];
function makeDiv(){
    var divsize = ((Math.random()*100) + 50).toFixed();
    var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
    $newdiv = $('<div/>').css({
        'width': ' 30 px', // sets width to constant
        'height': '10px', // sets height to constant
    // removes background-color property of div, but keeps
    // generating random colors that will be applied to the random words
    //    'background-color': color
    });
    // randomWord will accommodate for textArray of any size
    var randomWord = textArray[ (Math.floor(Math.random() * textArray.length)) ]
    var posx = (Math.random() * ($(document).width() - divsize)).toFixed();
    var posy = (Math.random() * ($(document).height() - divsize)).toFixed();
    // appends randomWord to new div
    $newdiv.text(randomWord).css({
        'position':'absolute',
        'left':posx+'px',
        'top':posy+'px',
        'display':'none',
        // adds randomly generated color to random word
        'color' : color 
    }).appendTo( 'body' ).fadeIn(100).delay(300).fadeOut(200, function(){
       $(this).remove();
       makeDiv(); 
    }); 
}

makeDiv();