简体   繁体   中英

How to keep a <div> tag inside a <div> when moving in Jquery

I have a problem on keeping a <div> inside a <div> . One of them moves, but if it goes too far, it goes out of the big one and the page. I am using Jquery to animate the <div> . Note: The little <div> moves horizontally.

Properties:
Big <div> :
Width: 600px


#truck is the little <div> .

My code(Jquery):

     function moveRight(){
     $('#truck').animate({
     'marginLeft' : "+=3px"
     });
     }
     function moveLeft(){
     $('#truck').animate({
     'marginLeft' : "-=3px" 
     });
     }//later code<br>
     window.addEventListener('keydown', function(evt){
     var key = evt.keyCode;
     if( key == 39){
     moveRight() = true;
     moveLeft() = false;
     }
     if( key == 37){
     moveLeft() = true;
     moveRight() = false;
     }

     }, false); 

Please help! There is no jsfiddle but I have google apis jquery.

can not give an exact answer without looking at HTML & CSS. but as I think

'marginLeft' : "-=3px"

when this line is executed, if the value of the margin-left get a negative value then inner <div> will go out of the range of outer <div> .

Same thing can be happened when below line is executed,

'marginLeft' : "+=3px

if the margin-left value is greater than the width of the outer <div> , even then inner <div> will go out of the range of outer <div>

You can check if your truck 's margin-left is below zero or beyond your container's width.

 function moveRight() { var left = $('#truck').css("marginLeft").match(/\\d+/g); if (left < 320) { $('#truck').animate({ 'marginLeft': "+=80px" }); } } function moveLeft() { var left = $('#truck').css("marginLeft").match(/\\d+/g); if (left >= 80) { $('#truck').animate({ 'marginLeft': "-=80px" }); } } //later code<br> window.addEventListener('keydown', function(evt) { var key = evt.keyCode; if (key == 39) { moveRight() = true; moveLeft() = false; } if (key == 37) { moveLeft() = true; moveRight() = false; } }, false); 
 #container { width: 400px; height: 40px; border: 1px solid black; } #truck { margin-left: 0px; width: 80px; height: 40px; background-color: #AAA; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <div id="container"> <div id="truck"></div> </div> 

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