在您的示例中,xandy将是视口外的第一个像素,位于其右下角。请记住,这些值是从 0 开始的。
例如,假设innerWidth是 5 并且innerHeight是 3。您将拥有:
[0, 0] [1, 0] [2, 0] [3, 0] [4, 0] [5, 0]
[0, 1] [1, 1] [2, 1] [3, 1] [4, 1] [5, 1]
[0, 2] [1, 2] [2, 2] [3, 2] [4, 2] [5, 2]
使用您当前的代码,[x, y]将是[5, 3],它将在这里:
[0, 0] [1, 0] [2, 0] [3, 0] [4, 0] [5, 0]
[0, 1] [1, 1] [2, 1] [3, 1] [4, 1] [5, 1]
[0, 2] [1, 2] [2, 2] [3, 2] [4, 2] [5, 2]
[5, 3]
要获得右下角的像素,您需要
return [window.innerWidth - 1, window.innerHeight - 1];
-1 是因为我们谈论的是单个像素,即 1x1。当然,您必须允许您添加的元素的任何宽度和高度。一个 10x10 的元素在两者上都需要 -10。
例子:
setTimeout(() => {
document.body.removeChild(document.getElementById("msg"));
const div = document.createElement("div");
div.className = "box";
document.body.appendChild(div);
div.style.left = (window.innerWidth - div.offsetWidth) + "px";
div.style.top = (window.innerHeight - div.offsetHeight) + "px";
}, 800);
/* Use border-box */
html {
box-sizing: border-box;
font-family: sans-serif;
}
*, *:before, *:after {
box-sizing: inherit;
}
/* Full viewport */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
/* Show a grey background */
body {
background-color: #eee;
}
/* Our box div */
.box {
position: absolute;
width: 10px;
height: 10px;
background-color: blue;
}
<div id="msg">Box will appear in the bottom-right in 800ms...</div>