元素不在定义区域内

Element not staying within defined area in javascript

本文关键字:区域 定义 元素      更新时间:2023-09-26

我编写了一个基本程序,用于在div元素中移动按钮。按钮不在我想要的位置。在HTML方面,我用id = "page"定义了DIV。这是js代码。为什么按钮不在DIV元素中?

var buttonState = document.getElementById("clickMe");
var maxWidth = document.getElementById("page");
var maxHeight = document.getElementById("page");
var pageWidth = maxWidth.clientWidth;
var pageHeight = maxHeight.clientHeight;
var screenWidth = 0;
var screenHeight = 0;
function moveButton() {
    "use strict";
    // Find max width and height of screen and set variables to random number within parameters
    screenWidth = Math.floor(Math.random() * (pageWidth)) + 1;
    screenHeight = Math.floor(Math.random() * (pageHeight)) + 1;  
    console.log(screenWidth);
    console.log(screenHeight);
    // Button position
    buttonState.style.left = (screenWidth) + "px";
    buttonState.style.top = (screenHeight) + "px";
    // Button size
    buttonState.style.width = buttonSize + "em";
    buttonState.style.height = buttonSize + "em";

在计算屏幕宽度和屏幕高度时,你需要考虑到按钮的大小。

div是基于左上角像素定位的,所以如果Math.random()最终返回1或非常接近它的值,除非你从最大值中减去按钮的大小,否则按钮将掉出页面。

var buttonWidthPx = buttonState.offsetWidth;
var buttonHeightPx = buttonState.offsetHeight;
screenWidth = Math.floor(Math.random() * (pageWidth - buttonWidthPx)) + 1;
screenHeight = Math.floor(Math.random() * (pageHeight - buttonHeightPx)) + 1;

还要确保将按钮的位置设置为相对位置,以便它位于div内,而不是绝对位置。

首先想到的可能是css布局问题,而不是javascript或html。

第一个线索是

buttonState.style.left
buttonState.syyle.top

如果你在Chrome DevTools中检查buttonState,你可能会发现布局是:绝对的,这将是一个很好的理由,为什么它没有按照预期布局。另一个可能是如果布局设置为static。

这里是一个链接,提供了很好的信息深度css布局设置:http://alistapart.com/article/css-positioning-101

我要尝试的第一件事是打开DevTools并取消选择(删除)buttonState的所有样式,直到你找到导致问题的布局。

我不知道您面临的确切问题,因为您没有提供任何HTML/CSS,但请查看此操作示例。

<div id="page">
    <button id="clickMe">Click Me</button>
</div>
<button id="move">Move Button</button>

#page {
    width:300px;
    height: 300px;
    background-color: whitesmoke;
}
#clickMe {
    position: relative;
    top: 0;
    left: 0;
}

var page = document.getElementById("page");
var pageWidth = page.clientWidth;
var pageHeight = page.clientHeight;
var button = document.getElementById("clickMe");
var buttonWidth = button.clientWidth;
var buttonHeight = button.clientHeight;
function moveButton() {
    var x = Math.floor(Math.random() * (pageWidth - buttonWidth));
    var y = Math.floor(Math.random() * (pageHeight - buttonHeight));
    button.style.left = x + "px";
    button.style.top = y + "px";
}
document.getElementById("move").onclick = moveButton;