javascript - How to follow mouse movement the opposite direction? -


i have div follows mouse coordinates opposite direction , within div .box. when move mouse red box should move opposite direction, looks kind of parallax effect. move on mouse speed , not want. box move slightly, see box move little bit opposite direction. , have align box center of mouse.

i have code script let red box follow mouse movement, doesn't know how above work.

$(document).ready(function(){   $('div.container').on('mousemove',function(e){         var x = e.pagex - this.offsetleft;         var y = e.pagey - this.offsettop;         $('div.box').css({'left': x, 'top': y});   }); }); 

hope can me out. thanks.

http://codepen.io/anon/pen/zbrkga

try change top bottom , left right may solve problem like,

$('div.box').css({'right': x, 'bottom': y}); 

$(document).ready(function() {    $('div.container').on('mousemove', function(e) {      var x = e.pagex - this.offsetleft;      var y = e.pagey - this.offsettop;      $('div.box').css({        'right': x,        'bottom': y      });    });  });
.container {    margin: 0 auto;    width: 300px;    height: 300px;    border: 1px #000 solid;    position: relative;  }  .box {    width: 50px;    height: 50px;    border: 1px #000 solid;    position: absolute;    right: 200px;    background: red  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  <div class="container">    <div class="box"></div>  </div>

updated, fixing box in 100px range delay

$(document).ready(function() {    $('div.container').on('mousemove', function(e) {      var x = (e.pagex - this.offsetleft);      var y = (e.pagey - this.offsettop);      if(x<100||x>200||y>200||y<100) return false;      settimeout(function() {        $('div.box').css({          'right': x,          'bottom': y        }).text(x+','+y);      }, 500);    });  });
.container {    margin: 0 auto;    width: 300px;    height: 300px;    border: 1px #000 solid;    position: relative;  }  .box {    width: 50px;    height: 50px;    border: 1px #000 solid;    position: absolute;    right: 200px;    background: red  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>  <div class="container">    <div class="box"></div>  </div>


Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -