我昨天问了this question,并被要求让一个新人得到精确答案。
单击按钮时,我的代码会在页面上显示单词。
它完美无缺,是否可以将其包含在容器中?
因为我希望这只能在手机上显示,当我缩小浏览器页面时,会有一个巨大的滚动条,并且所有单词都不显示在窗口中。
试试看,我试图在一个300x300px的盒子中包含它,但是到处都是。是可以使用引导网格还是任何媒体查询,或者像我对任何容器一样?或者它是另一个JavaScript规则?
再次感谢!
var words = [
'Hello',
'No',
'Hi',
'Banana',
'Apple'
];
var visible = 0;
document.querySelector("form").addEventListener("submit", function(e) {
e.preventDefault();
var fullWidth = window.innerWidth;
var fullHeight = window.innerHeight;
var elem = document.createElement("div");
elem.textContent = words[visible];
elem.style.position = "absolute";
elem.style.left = Math.round(Math.random() * fullWidth) + "px";
elem.style.top = Math.round(Math.random() * fullHeight) + "px";
document.body.appendChild(elem);
visible++;
});
<form>
<input type="submit">
</form>
答案 0 :(得分:1)
我改变了你的代码,这样就可以了。
var words = ['Hello','No','Hi','Banana','Apple'];
var visible = 0;
var container = document.getElementById("container");
var containerWidth = container.offsetWidth;
var containerHeight = container.offsetHeight;
document.querySelector("form").addEventListener("submit", function(e) {
e.preventDefault();
var elem = document.createElement("div");
elem.className = "elem";
elem.textContent = words[visible];
document.body.appendChild(elem); // to get div sizes
var left = Math.round(Math.random() * containerWidth);
var maxRight = containerWidth - (left + elem.offsetWidth + 5);
if (maxRight < 0) {
left -= Math.abs(maxRight);
}
var top = Math.round(Math.random() * containerHeight);
var maxBottom = containerHeight - (top + elem.offsetHeight + 5);
if (maxBottom < 0) {
top -= Math.abs(maxBottom);
}
elem.style.left = left + "px";
elem.style.top = top + "px";
container.appendChild(elem);
visible++;
});
#container {
border: 1px solid black;
height: 500px;
width: 500px;
position: relative;
}
.elem {
display: inline-block;
position: absolute;
}
<form>
<input type="submit">
</form>
<div id="container"></div>