我有硬币的图像。
我想给出一个从0到示例20的值。
0: no coin
1: to one coin
2: 2 coin etc
20: 20 coin
6枚硬币的集合应如下所示:
我如何实现这一目标?
答案 0 :(得分:0)
$(".coins").each(function(){
var $self = $(this);
var applyCoins = function(){
$self.empty();
var coins = $self.data("coins");
for (var i=coins-1; i>=0; i--) {
var $coin = $("<div></div>").addClass("coin").css("top", (i*20)+"px");
$self.append($coin);
}
};
$self.on("loadCoins", function(){
applyCoins();
});
applyCoins();
});
$("#button").click(function(){
$(".coins").data("coins", $("#input").val()).trigger("loadCoins");
});
&#13;
.coins {
width: 120px;
height: 120px;
position: relative;
overflow: visible;
}
.coins .coin {
width: 120px;
height: 120px;
position: absolute;
top: 0;
left: 0;
background-color: #FF0000;
border-bottom: 3px solid #333333;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p>
<input type="text" value="3" id="input" />
<input type="button" value="change" id="button" />
</p>
<div class="coins" data-coins="10"></div>
&#13;
答案 1 :(得分:0)
如果您更喜欢纯JS:
var maxI = Math.floor(Math.random() * (21 - 1)) + 1;
var marginCoins = 0;
var coin = [];
for (var i = 0; i < maxI; i++) {
coin[i] = document.createElement('img');
coin[i].src = 'http://placehold.it/75x75';
coin[i].style.position = 'fixed';
coin[i].style.top = marginCoins+'px';
coin[i].style.height = '75px';
coin[i].style.border = '1px solid black';
document.body.appendChild(coin[i]);
marginCoins += 45;
}