moving a div on mousemove inside another div

旧街凉风 提交于 2020-01-05 04:18:15

问题


I am trying to make a div which is inside a container div move in the opposite direction of the mouse on the X axis (only left and right).

this is what I have so far:

html

<div class="container">
    <div class="box"></div>
</div>

css

.container { width: 450px; height: 52px; border: 1px #000 solid; position: relative; }
.box { width: 50px; height: 50px; border: 1px #000 solid; position: absolute; right: 200px; }

jquery

$(document).ready(function(){
  $('div.container').mousemove(function(e){
        var x = e.pageX - this.offsetLeft;
      if ($('div.box').css('right') <= '400') {
          $('div.box').css({'right': x}); 
      }
  });
});

JSfiddle - http://jsfiddle.net/eyalbin/qQmu7/49/

for some reason the function stops working after a couple of seconds.

can anyone help please


回答1:


Try this : JSFiddle

You wrote

if ($('div.box').css('right') <= '400')

instead of

if (x <= 400)

:)




回答2:


This should do it

$(document).ready(function(){
  $('div.container').mousemove(function(e){
      var x = e.pageX - this.offsetLeft;
      if ((x <= 400)) {
          $('div.box').css({'right': x}); 
      }
  });
});

FIDDLE




回答3:


$(document).ready(function(){
   $('div.container').on('mousemove',function(e){
    var x = e.pageX - this.offsetLeft;

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

   });
});

Check This link Working fine dude...

Js Fiddle Demo




回答4:


$('#parent .child').mousemove( function(e) {


       var parent_x = this.offsetLeft; //get parent position
       var parent_y = this.offsetTop;      

       var mouseX   =  e.pageX; //get mouse move position
       var mouseY   =  e.pageY;

       var boxPositionX = mouseX-parent_x+5;
       var boxPositionY = mouseY-parent_y+5;

       $('.hover-box',this).css({'top': boxPositionY,'left': boxPositionX});
    });

///////// CSS

.hover-box{
   position:absolute;
}


来源:https://stackoverflow.com/questions/19270597/moving-a-div-on-mousemove-inside-another-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!