正在处理一个对象在屏幕上随机移动的项目。我试图在顶部有一个不被这些对象覆盖的元素。这是我当前的代码:
function makeNewPosition(){
// Get viewport dimensions
var h = $(window).height() - 150;
var w = $(window).width() - 100;
var nh = Math.floor(Math.random() * h);
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
这效果很好,但我需要在屏幕顶部遮挡物体无法到达的 150 像素。由于某种原因我一直无法做到这一点。我将如何修改我的代码来完成此任务?
感谢您的帮助!
最佳答案
您需要将 150px
设置为距顶部的偏移量。否则,对象不会触及屏幕的底部
150px,而不是顶部
。
function makeNewPosition() {
var h = $(window).height() - 150;
var w = $(window).width() - 100;
var nh = Math.floor(Math.random() * h) + 150;
var nw = Math.floor(Math.random() * w);
return [nh,nw];
}
如果想让100px
的左右区域也保持不变,则需要减去200px
并加上100px
结果。
function makeNewPosition() {
var h = $(window).height() - 150;
var w = $(window).width() - 200;
var nh = Math.floor(Math.random() * h) + 150;
var nw = Math.floor(Math.random() * w) + 100;
return [nh,nw];
}
关于javascript - 如何设置自定义窗口高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38852450/