制作响应式动态 div-s 方 block 的最简单方法是什么,就像内存游戏一样(下图)。
我遇到的问题是用户需要向下滚动才能看到游戏的整个底部部分。我如何计算(最简单的解决方案)我的整个游戏始终可见。而且我希望它是动态的(在图像上我们可以看到 4x4 游戏,应该适用于任何数字,7x7、10x10 等等......)。
我的代码片段是:http://jsbin.com/nucovakevu/edit?html,css,output 。 中的所有内容都是由 JavaScript 动态添加的。 在我放大的地方它也不起作用。 我是前端开发的初学者,我在这里混合了 Bootstrap 和纯CSS,这可能不是一个好的解决方案。 我还使用了这个 css 技巧来使我的 div 成为响应式正方形:
width: 23%;
height: 15vw;
它应该是这样的:
width: 23%;
height: 23vw;
但是在这种情况下我得到了矩形,因为我显然不太明白它是如何工作的。
最佳答案
只需调用函数size()即可;每当您想更新网格时。
查看代码中的注释以更好地了解其功能。
https://jsfiddle.net/xn5j4rcf/
window.addEventListener('load', function() {
size();
});
function size() {
var container = document.getElementById('container');
container.innerHTML = '';//don't want any extra boxes when you call this function again
var x = Math.floor(window.innerWidth / 50);//width of boxes that can fit; remove any decimal places
var y = Math.floor(window.innerHeight / 50);//height of boxes that can fit; remove any decimal places
for (var i = 0; i < x * y; i++) {//multiply x*y to get total area of boxes that can fit
var box = document.createElement('div');//create a div
box.className = 'box';//assign class
container.appendChild(box);//append
}
}
window.addEventListener('resize', function() {
size();//call the function again when the window is resized
});
.box {
width: 50px;
height: 50px;
padding: 4px;
-o-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
-ms-box-sizing: border-box;
box-sizing: border-box;
display: inline-block;
border: 4px solid #fff;//border for margin but use border-box to make sure the width and height are still 50px
background-color: #ddd;
}
html,
body {
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
#container {
font-size: 0;//remove annoying margin from display:inline-block;
}
<div id="container">
</div>
关于javascript - 为内存游戏制作动态方形 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34458805/