2014-04-27 22 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