简体   繁体   中英

move DOM element position dynamically

I'm generating spans dynamically and placing their location as such:

        $('#myObstacles').append("<span id=\"" +  test + randX + "\">" + items[randObj] + "</span>");
        document.getElementById("test"+randX).style.position="absolute";
        document.getElementById("test"+randX).style.left=randX;
        document.getElementById("test"+randX).style.top=randY;

Then I have setInterval() function that should move these DOM spans every so often by calling moveSpans() :

    function moveSpans() {
        $("#myObstacles span").each(function (index, val) {
            val.style.top-=10;
        });
    }

For some reason, the appended DOM spans to #myObstacles don't change position.

Why is this?

As Wlises said, you need to stick with the jQuery methods or the core JavaScript methods; if you're using a jQuery object (which is returned in callback functions as val like in the one above), stick with the jQuery method .css() .

Therefore:

  • GOOD : val.css("top","-=10")
  • BAD : val.style.top -= 10 (This is a native JavaScript property, but for jQuery objects, there is NO style property. There is only the .css() accessor/mutator method.)

Since you are trying to decrement top by 10px, it is acceptable to use: val.css("top","-=10")

Here's an explanation straight from the jQuery documentation:

As of jQuery 1.6, .css() accepts relative values similar to .animate() . Relative values are a string starting with += or -= to increment or decrement the current value. For example, if an element's padding-left was 10px, .css( "padding-left", "+=15" ) would result in a total padding-left of 25px.

In the "function(index, val)" the "val" is a jQuery object, try:

function moveSpans() {
    $("#myObstacles span").each(function (index, val) {
        $(val).css({top: -10});
    });
}

Have you tried this?

function moveSpans() {
    $("#myObstacles span").each(function (index, val) {
        var $el = $(val)
        $el.css({top: $el.css("top")-10});
    });
}

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