javascript - jQuery - How to make a div follow a cursor... within its center - Stack Overflow

So this is what I got.<div class="box"><div>.box {position: absolute;left: 0;top

So this is what I got.

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

 .box {
 position: absolute;
 left: 0;
 top: 0;
 width: 100px;
 height: 100px;
 background: yellow;
 }

 $(document).bind('mousemove', function(e){
 $('.box').css({
 top: e.pageY
 left:  e.pageX,
 });
 });

It works. The box follow the cursor. Problem is it follow the EDGE of the cursor. ie, the cursor holds the top left corner of the box. I want it to hold the center of the box, or another point that's not the edge. Any ideas how to do that?

Sorry if this dumb. I'm good enough with HTML/CSS but just starting with javascript and jQuery.

So this is what I got.

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

 .box {
 position: absolute;
 left: 0;
 top: 0;
 width: 100px;
 height: 100px;
 background: yellow;
 }

 $(document).bind('mousemove', function(e){
 $('.box').css({
 top: e.pageY
 left:  e.pageX,
 });
 });

It works. The box follow the cursor. Problem is it follow the EDGE of the cursor. ie, the cursor holds the top left corner of the box. I want it to hold the center of the box, or another point that's not the edge. Any ideas how to do that?

Sorry if this dumb. I'm good enough with HTML/CSS but just starting with javascript and jQuery.

Share Improve this question asked Nov 3, 2016 at 5:27 Magdi GamalMagdi Gamal 6781 gold badge12 silver badges28 bronze badges 1
  • there is an error on your line of codes there should be a ma after the pageY – Rani Moreles Rubillos Commented Nov 3, 2016 at 5:33
Add a ment  | 

1 Answer 1

Reset to default 6

Use this code instead

 $(document).bind('mousemove', function(e){
   $('.box').css({
     top: e.pageY - $(".box").height()/2, // just minus by half the height
     left:  e.pageX - $(".box").width()/2 // just minus by half the width
   });
 });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745404980a4626273.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信