简体   繁体   中英

dynamic change in javascript, won't move my div

Hi there fellow programmers!

I Want to be able to type in to the boxes how much px i want my div to move. But it won't move and I cant see whats wrong with my code. Can someone with fresh eyes spot the problem?

Any help is much appreciated!

Here's the code so far:

<!DOCTYPE html>
<html lang="sv">

<head>
    <meta charset="utf-8">
    <title> javascript</title>

    <style>
        #changeme {
            background-color: lightblue;
            position: absolute;
        }

    </style>

    <script>
        var $Rob = {};

        $Rob.moveUpp = 0;
        $Rob.moveLeft = 0;
        $Rob.elementid = "";


        $Rob.move = function(elementid, movex, movey)

        {
            $Rob.moveUpp = movey;
            $Rob.moveLeft = movex;
            $Rob.elementid = elementid;

            $Rob.movesoft();
        }

        $Rob.movesoft = function() {
            var elem = document.getElementById($Rob.elementid);
            if ($Rob.moveUpp > 0) {

                elem.style.top = (parseInt(elem.style.top) + 1) +
                    "px";
                $Rob.moveUpp--;

            } else if ($Rob.moveUpp < 0) {
                elem.style.top = (parseInt(elem.style.top) - 1) +
                    "px";
                $Rob.moveUpp++;
            }

            if ($Rob.moveUpp != 0) {
                setTimeout($Rob.movesoft, 100);
            }

        }

    </script>

</head>

<body>

    <h1> Dynamic changes </h1>

    <form>
        <p>Move right:</p> <input value="0" type="text" id="moveRight" />



        <p>Move down: </p> <input value="0" type="text" id="moveDown" />

        <input type="button" value="Move" onClick="$Rob.move(document.getElementById('changeme'),parseInt(document.getElementById('moveRight').value),parseInt(document.getElementById('moveDown').value));" />
    </form>

    <div id="changeme" style="top: 100px;left: 100px;"> Hello </div>

</body>

</html>

All the best I love Stackoverflow and its members! cheers

// Mcgayjver

You're doing:

$Rob.move(document.getElementById('changeme'), x, y) .

When you should just be doing:

$Rob.move('changeme, x, y)

Because $Rob.move expects an elementID string as a first parameter, not an actual HTMLElement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM