Closed. This question is opinion-based。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗?更新问题,以便editing this post用事实和引用来回答。
                        
                        已关闭6年。
                                                                                            
                
        
我只是在尝试一些想法,目前对网站布局有一个想法,其中涉及将网页上特定元素的样式随机化。例如,如果我在一个页面上有10个段落,我希望每个段落都具有随机的字体大小,字体和颜色。

这些样式可以动态生成,也可以从样式表中存在的一组随机样式中获取。

如果有人对实现这一目标的最新解决方案有任何想法,将感激所有想法,也许我在搜索错误的术语,但到目前为止Google并没有真正给我任何思想。

最佳答案

如果要确保段落中的每个样式都是唯一的,则应创建一个包含要应用于每个元素的所有样式的数组,并对其进行混洗:

JSFiddle



的HTML

<div class="myParagraphs">
    <p>1</p>
    <p>2</p>
    <p>3</p>
</div>


Javascript(Fisher-Yates shuffle algorithm提供的代码here

随机排列一系列CSS类名称,并将其应用于您的段落。

/* Fisher-Yates Shuffle                          */
/* See https://stackoverflow.com/a/6274398/464188 */
function shuffle(array) {
    var counter = array.length, temp, index;

    // While there are elements in the array
    while (counter > 0) {
        // Pick a random index
        index = Math.floor(Math.random() * counter);

        // Decrease counter by 1
        counter--;

        // And swap the last element with it
        temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }

    return array;
}

var stylesArray = ["class1", "class2", "class3"];
var myStyles = shuffle(stylesArray);

$('.myParagraphs > p').each(function(index, value) {
    $(this).addClass(myStyles[index]);
});


的CSS

.class1 {
    color: green;
}

.class2 {
    color: red;
}

.class3 {
    color: orange;
}

关于javascript - 如何最好地在同一页面上显示不同文本元素的随机样式? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19139181/

10-09 18:05
查看更多