使用JavaScript使用变量更改边距

时间:2014-12-27 02:41:23

标签: javascript html css

我试图在点击向上箭头键时更改top margin的值,代码似乎对我来说,但我不知道为什么它不会工作!

JavaScript

var playerPosition = 0;

window.onkeyup = function(e) {
    var key = e.keyCode ? e.keyCode : e.which;

    if(key = 38) {
        playerPosition += 10;

    } else if(key = 40) {
        playerPosition -= 10;
    }

    document.getElementsByClassName('player').style.marginTop = playerPosition+".px";

 }

HTML / CSS

.mainDiv {
        display: block;
        position: absolute;
        margin: auto;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: black;
        width: 600px;
        height: 400px;
    }
    .player {
        position: absolute;
        background-color: #FFF;
        width: 5px;
        height: 70px;
        margin: 20px 0 0 10px;
        padding: 0 0 0 0;
    }
    .bar {
        top: 30px;
        height: 100%;
        width: 5px;
        border-style: dashed;
        border-left: 5px;
        border-color: #FFF;
        position: fixed;
        left: 50%;
    }
    .ai {
        position: absolute;
        right: 10px;
        background-color: #FFF;
        width: 5px;
        height: 70px;
        margin: 164px 0 0 10px;
        padding: 0 0 0 0;
    }

    .ball {
        position: absolute;
        left: 50px;
        bottom: 69px;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background-color: #FFF;
    }
    </style>
    <script src="sprite.js" defer="defer"></script>
</head>
<body>
    <div class="mainDiv">
        <div class="player"></div>
        <div class="bar"></div>
        <div class="ai"></div>
        <div class="ball"></div>
    </div>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

getElementsByClassName返回一个HTMLCollection。因此,您必须指定要工作的元素。

例如:

document.getElementsByClassName('player')[0].style.marginTop = playerPosition+".px";

答案 1 :(得分:1)

document.getElementsByClassName('player')返回NodeList个具有类player的元素(类似数组)。您需要遍历列表并将样式更改应用于每个:

var players = document.getElementsByClassName('player');
for(var i = 0; i < players.length; i++)
    players[i].style.marginTop = playerPosition+"px";

或者我想如果你只有一个,就把它应用到第0个元素。

fiddle

答案 2 :(得分:1)

函数被称为&#34; getElements [...]&#34;,复数,因此它返回一个带有类名的HTML元素数组。此外,在条件语句中,您使用赋值运算符(=)而不是比较运算符(==)。 jsfiddle

document.getElementsByClassName('player')[0].style.marginTop = playerPosition+"px";