2014-04-27 14 views
0

所以我发现this已经在这里,它几乎正是我想要的。唯一的区别是,而不是创建箱子,我想他们是从一个数组中的词 - 就像使用javascript或jquery的随机词弹出脚本

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(); 
    }); 
})(); 
+0

所以你应该改变“背景色”与“色”,删除divsize,并且使用的Math.random调用1之间的随机数(约直列下面列出的变化评论)和数组的长度,并将数组中的值放入一个变量中,即“在div中添加”。 这些只是快速提示,我相信你可以自己做; – astrodedl

回答

0

这是怎么回事? 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(); 
+0

你好,如果你发现任何有用的答案,请选择一个作为正式答案。建筑声誉在这个网站上有很大的帮助。谢谢! – LexJacobs