我试图使用Jquery和CSS显示字母的字母(随机)作为div的背景图像,但是,我希望每个元素的字母是随机的,但是我只能将所有图像随机化为同时:
HTML:
<div class="randbg"></div>
<div class="randbg"></div>
<div class="randbg"></div>
<div class="randbg"></div>
JS
(function($) {
$.fn.RandBG = function(options) {
var settings = $.extend({
ClassPrefix: "bg",
count: 26
}, options);
var index = Math.ceil(Math.random() * settings.count * settings.count) % settings.count;
$(this).addClass(settings.ClassPrefix + index);
};
}(jQuery));
CSS
.randbg {
margin:20px auto;
font-family: 'Parkour';
color:red;
width:180px;
height:180px;
}
.randbg:before {
display:block;
font-size:10em;
text-align: center;
vertical-align: center;
background-color:#EDEDED;}
.randbg.bg0:before {
content:"z";
}
.randbg.bg1:before {
content:"a";
}
.randbg.bg2:before {
content:"b";
}
.randbg.bg3:before {
content:"c";
}
.randbg.bg4:before {
content:"d";
}
.randbg.bg5:before {
content:"e";
}
.randbg.bg6:before {
content:"f";
}
.randbg.bg7:before {
content:"g";
}
.randbg.bg8:before {
content:"h";
}
.randbg.bg9:before {
content:"i";
}
.randbg.bg10:before {
content:"j";
}
.randbg.bg11:before {
content:"k";
}
.randbg.bg12:before {
content:"l";
}
.randbg.bg13:before {
content:"m";
}
.randbg.bg14:before {
content:"n";
}
.randbg.bg15:before {
content:"o";
}
.randbg.bg16:before {
content:"p";
}
.randbg.bg17:before {
content:"q";
}
.randbg.bg18:before {
content:"r";
}
.randbg.bg19:before {
content:"s";
}
.randbg.bg20:before {
content:"t";
}
.randbg.bg21:before {
content:"u";
}
.randbg.bg22:before {
content:"v";
}
.randbg.bg23:before {
content:"w";
}
.randbg.bg24:before {
content:"x";
}
.randbg.bg25:before {
content:"y";
}
让每个randbg div显示随机字母的最佳方法是什么?
由于
答案 0 :(得分:3)
问题是你的插件。您将同一个类应用于所有匹配的元素。我假设你像这样称呼它
$('.randbg').RandBG();
您有多种选择,但我可能会使用addClass()
的回调版本
$.fn.RandBG = function(options) {
var settings = $.extend({
classPrefix: "bg",
count: 26
}, options);
return this.addClass(function() {
return settings.classPrefix + Math.floor(Math.random() * settings.count);
});
};
您还应该记得始终从插件函数返回jQuery集合(this
),以便他们重新chainable。