简体   繁体   中英

How can I make my div element move more than 200px?

I've been working on a project using jQuery where i have a div element that says "click," and when you try to click on it, it moves to a random location within the window. The issue I'm having is that every once in a while the div will move only a little bit, leaving the cursor still inside of the div, allowing the user to click on the link.

I'm fairly new at javascript and I'm not too sure how I should go about doing something like this.

I was thinking I could do something like subtracting the new position from the old one and checking to see if they have a difference of less than 200px, and if they do, recalculating the numbers. If that isn't how you would do it, I'm completely open to other methods.

 function setPosition() { var randY = Math.floor(Math.random() * (window.innerHeight - 200)); var randX = Math.floor(Math.random() * (window.innerWidth - 200)); $('#square').animate({ top: randY + 'px', left: randX + 'px' }, 200); } $(document).ready(function() { setPosition() var tries = 0; //tries is just to stop it after it reaches 1000. //I'm planning to make some kind of page to congradulate you on wasting your time. $('#square').mouseenter(function() { if (tries < 1000) { setPosition(); tries += 1; console.log(tries) } }); }); 
 #square { background: orange; height: 115px; width: 150px; position: relative; text-align: center; padding-top: 35px; } h3, h3 * { font-family: "Comic Sans MS", cursive, sans-serif; font-size: 20px; vertical-align: middle; position: relative; color: black; text-decoration: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <head> <link rel=stylesheet type=text/css href=square.css> <script src=jquery-1.11.3.min.js></script> <script src=square.js></script> </head> <body> <div id=square> <h3><a href=''>Click</a></h3> </div> </body> </html> 

I'm thinking you might want to run your randomization logic until it finds a combination that is more than 200 pixels away from it's current location.

Off the top of my head, that'd be something like this:

function setPosition() {
   var $square = $('#square');
   var prevY = $square.offset().top;
   var prevX = $square.offset().left;
   var randY, randX;

   do {
       randY = Math.floor(Math.random() * (window.innerHeight - 200));
       randX = Math.floor(Math.random() * (window.innerWidth - 200));
   } while( Math.abs(randY - prevY) < 200 || Math.abs(randX - prevX) < 200 );

   $square.animate({
     top: randY + 'px',
     left: randX + 'px'
   }, 200);
 }

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