问题描述
假设屏幕尺寸为 1920by1080,那么我想要用户输入的 div 假设说 200by200
那么这些尺寸的 div 应该创建整个屏幕。我如何使用 HMTL、CSS 和 javascript 做到这一点。
CSS 代码
div {
height: 200px;
width: 200px;
background-color: red;
padding-bottom: 20px;
Box-shadow: 2px 2px 8px rgba(0,0.3);
border-style: solid;
display: inline-block;
}
HTML 代码
<input type="number" placeholder="enter height of div" id="div_height" />
<input type="number" placeholder="enter width of div" id="div_width" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
JAVASCRIPT
function myFunction() {
let height_div = document.getElementById('div_height').value;
let width_div = document.getElementById('div_width').value;
var xy = '',i,size = 20;
var x = screen.availHeight;
var y = screen.availWidth;
while (x > height_div) {
while (y > width_div) {
xy = xy + '<div>' + '</div>';
y = y - width_div;
}
x = x - height_div;
}
document.getElementById('demo').innerHTML = xy;
console.log(height_div + ' ' + width_div);
document.getElementsByTagName('div').style.height = height_div + 'px';
document.getElementsByTagName('div').style.width = width_div + 'px';
解决方法
尝试使用此代码:
div
{
position: fixed;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
然后它会覆盖整个屏幕。
,function myFunction(e) {
e.preventDefault()
let height_div = document.getElementById("div_height").value;
let width_div = document.getElementById("div_width").value;
var xy = "";
const xi = Math.floor(window.innerWidth / width_div);
const yi = Math.floor(window.innerHeight / height_div);
for (let i = 0; i < yi; i++) {
xy += "<div class='row'>";
for (let j = 0; j < xi; j++) {
xy += "<div></div>"
}
xy += '</div>'
}
console.log(xy)
document.getElementById("demo").innerHTML = xy;
console.log(height_div + " " + width_div);
Array.from(document.getElementsByTagName("div")).map(el => (el.style.height = height_div + "px"));
Array.from(document.getElementsByTagName("div")).map(el => (el.style.width = width_div + "px"));
}
document.querySelector("form").addEventListener('submit',myFunction);
div {
box-sizing: border-box;
height: 200px;
width: 200px;
background-color: red;
box-shadow: 2px 2px 8px rgba(0,0.3);
border-style: solid;
flex-grow: 0;
flex-shrink: 0;
}
.row {
display: flex;
}
p#demo {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
margin: 0;
z-index: 1;
}
.form {
background: blue;
position: relative;
z-index: 2;
}
<form class="form">
<input type="number" placeholder="enter height of div" id="div_height" />
<input type="number" placeholder="enter width of div" id="div_width" />
<button>Try it</button>
</form>
<p id="demo"></p>
尝试这样的事情,
如果你想填补空白并有一点宿醉,你可以使用Math.ceiling