Poruszanie się obiektu JavaScript

0

Witam!
Chciałbym zrobić prosty programik, który będzie polegał na tym, że przycisk będzie się poruszał po ekranie po skosie. Jednak porusza się tylko w lewą stronę. Jak to zmienić?

<body>
    <div id="content">
        <input id="but" type="button" value="Click me!" />
    </div>
    <script type="text/javascript">
        var interval;
        var but = document.getElementById("but");
        var left = 0;
        var top = 0;
        
        function run(){
            left += 5;
            top += 5;
            but.style.left = marginLeft + "px";
            but.style.top = marginTop + "px";
        }
        window.onload = function(){
            interval = setInterval(run,50);
        }
    </script>
</body>
1

Nie powinieneś używać top jako nazwy zmiennej:

top – This one is most often used in combination with a variable named left to determine or set element coordinates. Once again, the problem is that top is a host object, it points to the outermost window object and is most useful when used from within a frame. (proof)

Źródło: https://www.nczonline.net/blog/2007/06/03/javascript-variable-names-you-shouldn-t-use/

Zmień nazwę zmiennej top np na topPx.

0

Hej. Tutaj masz działający kod:

<body>
<input id="but" type="button" value="Click me!"/> 

  	<script type="text/javascript">
        var but = document.getElementById("but");
        var direction;
        var currentValue = 0;

        but.style.position = "absolute";
 
        function run(){
            if(currentValue == 500) direction = -5;
            if(currentValue == 0) direction = 5;

            currentValue += direction;

            but.style.left = currentValue + "px";
            but.style.top = currentValue + "px";

        }
        window.onload = function(){
            var interval = setInterval(run,50);
        }
    </script>
</body>

Szybkie wytłumaczenie:

currentValue przechowuje wartości dla stylu, direction przechowuje tak jakby kierunek. Sprawdzana jest aktualna pozycja (currentValue i w zależności od jej wartości if'y ustawiają wartość direction na plus lub minus. Mam nadzieję, że nie za bardzo zagmatwanie tłumaczę :D

0

Dzięki, zadziałało :)

1 użytkowników online, w tym zalogowanych: 0, gości: 1