元素未停留在javascript

时间:2015-07-27 18:46:16

标签: javascript size element

我编写了一个基本程序,可以在DIV元素中移动按钮。按钮不在我想要的区域内。在HTML方面,我有代码,用ID ="页面"定义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";

3 个答案:

答案 0 :(得分:0)

首先想到的是,它可能比javascript或html更像是css布局问题。

第一个线索是

buttonState.style.left
buttonState.syyle.top

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

以下链接提供了有关css布局设置的详细信息:http://alistapart.com/article/css-positioning-101

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

答案 1 :(得分:0)

在screenWidth和screenHeight的等式中,您需要考虑按钮的大小。

div基于左上角的像素定位,所以如果最终Math.random()返回1或非常靠近它的东西,除非你从maxes中减去按钮大小,否则该按钮将会脱离页面

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内部,而不是文档的绝对位置。

答案 2 :(得分:0)

我不知道你所面临的确切问题是因为你没有提供任何HTML / CSS,但请查看this小提琴以获得一个有效的例子。

#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;
git push <your_bit_bucket_remote> <revision>:refs/heads/<branch_name_at_bitbucket>
相关问题