如何在“ ArrowDown”和“ ArrowUp”键按下的窗口中使div居中?

时间:2019-01-07 23:36:56

标签: javascript

我需要在Javascript中建立逻辑的帮助,该逻辑将根据divArrowUp {{1}将ArrowDown的位置设置到窗口的中心}}事件。我无法建立良好的逻辑,需要帮助。

keydown

index.html:
window.onbeforeunload = function () {
    this.scrollTo(0, 0);
}

var content = document.getElementById("content"),
     current = 0;

for (var y=0;y<100;y++) {
    var box = document.createElement("div");
    box.id = "box";
    box.innerHTML = "Box - " + (y+1);
    content.appendChild(box);
}

window.onkeydown = function(e) {
    e.preventDefault();
    if (e.key === "ArrowUp") {
        if (current > 0) {
            current--;
            window.scrollTo(0, content.children[current].offsetTop - content.children[current].clientHeight);
        }
    } else if (e.key === "ArrowDown") {
        if (current < 100) {
            current++;
            window.scrollTo(0, content.children[current].offsetTop + content.children[current].clientHeight);
        }
    }
}
body {
    margin: 0;
}

#box {
    position: relative;
    height: 500px;
    width: 100%;
    margin: 5% auto 5% auto;
    color: black;
    background-color: skyblue;
    border: black 1px solid;
    font-size: 50px;
    text-align: center;
}

0 个答案:

没有答案