JS make an element move using .css

I wanted the element to move along the arrow using .css (), but it doesn’t work at all, and I cannot understand why. Exactly the same code works fine with JQ animate (). Can you explain to me why .css is not working? I know there are better ways to do this, but I'm just wondering why it doesn't attach the top property. Below is the animation code

$(document).ready(function(){
    $('body').keydown(function() {
        if (event.which == 38)
        {
            $('div').animate({top:'-=10px'},'fast');
        }
        else if (event.which == 40)
        {
            $('div').animate({top:'+=10px'},'fast');
        }
        else if (event.which == 37)
        {
            $('div').animate({left:'-=10px'},'fast');
        }
        else if (event.which == 39)
        {
            $('div').animate({left:'+=10px'},'fast');
        }
    }); 
});
+4
source share
3 answers

Using a .css()property for setting requires that the property be explicitly set in advance, while it .animate()will adjust the calculated position of the element without its special purpose.

#movable element top left <div>. , .css(), <divs>, , <div> top left.

$(document).ready(function(){
    $('body').keydown(function(event) {
        if (event.which == 38)
        {
            $('div').css({top:'-=10px'});
        }
        else if (event.which == 40)
        {
            $('div').css({top:'+=10px'});
        }
        else if (event.which == 37)
        {
            $('div').css({left:'-=10px'});
        }
        else if (event.which == 39)
        {
            $('div').css({left:'+=10px'});
        }
      
      //added to stop Qaru scrolling
      event.preventDefault();
    }); 
  
  
});
div {
  position:relative;
}

/* Set top and left of the movable div explicitly */
#movable {
  top:0px;
  left:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="movable">movable</div>
<div>immovable</div>
+2

div , position:absolute

+2

Is the code in the message your real code? Since you are using a variable event, but you have not defined any argument to the function passed to keydown. It should be $('body').keydown(function(event) {.

+1
source

All Articles