好的,我有一些自举缩略图设置了一个脚本,可以将缩略图内的图像或a
内的li
元素进行混洗。除了某些图像比其他图像更大/更小外,这些部分工作正常。我想让图像在shuffle上调整大小以匹配<li class="span#">
中允许的空间这是否可以在javascript中使用我的函数?
Bootstrap缩略图:
<ul class="thumbnails" id="list">
<li class="span4">
<a href="#" class="thumbnail">
<img src="http://placehold.it/360x270" alt="">
</a>
</li>
<li class="span3">
<a href="#" class="thumbnail">
<img src="http://placehold.it/260x120" alt="">
</a>
</li>
<li class="span2">
<a href="#" class="thumbnail">
<img src="http://placehold.it/160x120" alt="">
</a>
</li>
<li class="span3">
<a href="#" class="thumbnail">
<img src="http://placehold.it/260x120" alt="">
</a>
</li>
<li class="span2">
<a href="#" class="thumbnail">
<img src="http://placehold.it/160x120" alt="">
</a>
</li>
<li class="span3">
<a href="#" class="thumbnail">
<img src="http://placehold.it/260x120" alt="">
</a>
</li>
<li class="span2">
<a href="#" class="thumbnail">
<img src="http://placehold.it/160x120" alt="">
</a>
</li>
<li class="span3">
<a href="#" class="thumbnail">
<img src="http://placehold.it/260x120" alt="">
</a>
</li>
<li class="span2">
<a href="#" class="thumbnail">
<img src="http://placehold.it/160x120" alt="">
</a>
</li>
<li class="span3">
<a href="#" class="thumbnail">
<img src="http://placehold.it/260x120" alt="">
</a>
</li>
<li class="span2">
<a href="#" class="thumbnail">
<img src="http://placehold.it/160x120" alt="">
</a>
</li>
<li class="span2">
<a href="#" class="thumbnail">
<img src="http://placehold.it/160x120" alt="">
</a>
</li>
</ul>
Javascript:
<script> window.onload = function()
{
$('ul#list li img').shuffle();
};
</script>
<script>
(function($){
$.fn.shuffle = function() {
var allElems = this.get(),
getRandom = function(max) {
return Math.floor(Math.random() * max);
},
shuffled = $.map(allElems, function(){
var random = getRandom(allElems.length),
randEl = $(allElems[random]).clone(true)[0];
allElems.splice(random, 1);
return randEl;
});
this.each(function(i){
$(this).replaceWith($(shuffled[i]));
});
return $(shuffled);
};
})(jQuery);
</script>
span#
在css中看起来像这样:
.span4 {
width: 300px;
}
.span3 {
width: 220px;
}
.span2 {
width: 140px;
}
答案 0 :(得分:0)
烨。基本上找到最近的li并使用它的宽度/高度:
$.fn.shuffle = function() {
var allElems = this.get(),
getRandom = function(max) {
return Math.floor(Math.random() * max);
},
shuffled = $.map(allElems, function(){
var random = getRandom(allElems.length),
randEl = $(allElems[random]).clone(true)[0];
allElems.splice(random, 1);
return randEl;
});
this.each(function(i){
// find nearest li and use its width / height
var li = $(this).closest('li');
var height = li.height();
var width = li.width();
$(this).height(height);
$(this).width(width);
$(this).replaceWith($(shuffled[i]));
});
return $(shuffled);
};
答案 1 :(得分:0)
不是改组img元素,而是可以像这样改变li元素:
$('ul#list li').shuffle();
我用你的代码创建了一个小提琴,它似乎工作得很好:Check it out
如果你不能这样做,另一种选择是将span类直接添加到你的img元素。