0

我正在尝试将 .appendChild() 元素添加到我的视口中,而不会在浏览器窗口中引入垂直/横向滚动。如果我将 x 和 y 值设置为 window.innerWidth 和 window.innerHeight,则该元素会出现在我的视口之外。我怎样才能解决这个问题?

宽度和高度函数:

function XY() {
let x = window.innerWidth;
let y = window.innerHeight;
return [x, y];
}

视口: 在此处输入图像描述

添加元素后: 在此处输入图像描述

^请注意添加了垂直和水平滚动条。

4

1 回答 1

0

在您的示例中,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>

于 2020-02-12T07:23:59.430 回答