我通过将其他人的几个不同的例子拼凑在一起来组合一个Codepen,以便得到一些非常接近我真正想要的东西。我现在唯一的问题是我想在我的例子中给出一个默认值为3的按钮,而不是让某人输入他们选择的值,这样当点击按钮时,会选择三个图像随意。
我已经尝试了
$(shuffle($all).slice(0, $("input").val(3))).addClass("selected");
虽然评论了输入类型,但是没有用。
提前感谢任何提示!
http://codepen.io/asyi/pen/XMVwVg
<head>
<link rel="stylesheet" type="text/css" href="styles/style.css"> <title>This Webpage</title>
</head>
<body>
<div id="container">
<div class="square">
</div>
<div class="square">
</div>
<div class="square">
</div>
<div class="square">
</div>
</div>
<button>Click to win!:</button>
<input type="text" size="3" value="3" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="scripts/script.js"></script>
</body>
CSS
* {
box-sizing: border-box;
}
#container {
width: 100%;
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
#container > div {
width: 50%;
height: 20vw;
border: white 10px solid;
}
.selected {
background: tan;
border: red 2px solid;
}
.square {
background-image: url('https://placebear.com/300/200');
background-repeat: no-repeat;
background-size: 85%;
background-position: center;
}
的jQuery
$(document).ready(function(){
function shuffle(array) {
var m = array.length, t, i;
// While there remain elements to shuffle…
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}
$(function() {
$("button").click(function() {
var $all = $(".square").removeClass("selected");
$(shuffle($all).slice(0, $("input").val())).addClass("selected");
});
});
});