jQuery move divs according to mouse position

ぐ巨炮叔叔 提交于 2019-12-10 10:23:55

问题


I got a little Problem with jQuery, maybe you guys can help me. Here's the HTML Markup in jfiddle for better understanding:

jsfiddle

I'd like to have the div called #move_me to move either to the right or to the left side within the #content_wrapper according to the mouse position inside #content_wrapper.

Basically what I want is: if I move my cursor inside the #content_wrapper div to the right then the #move_me div should move to the left to see content2 div, when I move to the left the #move_me div should move to the right to see content1 div..

I tried to get it to work with mousemove and pageXoffset but I didn't get it to work.

something like this:

$('#content_wrapper').mousemove(function(e){
var x = e.pageX - this.parentoffsetLeft;
$('#move_me').css({'left': x}); 
});

HERE IS AN IMAGE EXPLAINING MORE PRECISELY:

Illustration http://www.22labs.com/moveme.jpg


回答1:


Working DEMO

Try this

I guess this is what you need, Add position:relative; to your move_me

code

$('#content_wrapper').mousemove(function (e) {

    $('#move_me').animate({
        'left': -e.pageX + 15 + 'px'
    }, 0);

});

Hope this helps, Thank you




回答2:


I partly wrote a solution. Hope this is what you need.

http://jsfiddle.net/NukSy/4/

$('div#content1').mousemove(function(p) {     
    $("div#content1").css('left', p.pageX + moveLeft);
    $("div#content2").animate({left: "0px"}, 500);
  });

Regards :))




回答3:


<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).mousemove(function(event){
$("div").attr("style","padding-left:"+event.pageX+"px; padding-top:"+event.pageY+"px");
});
});
</script>

<div style="">
<form>
<input type="text" placeholder="username" />
<input type="password" placeholder="password" />
<input type="submit" value="submit"/>
</form>
</div>


来源:https://stackoverflow.com/questions/18338608/jquery-move-divs-according-to-mouse-position

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