简体   繁体   中英

jQuery mousemove with CSS transitions

I'm making a game that involves clicking and dragging using jQuery. When you click inside the game div (red), a black block appears that you can drag around. I made a fiddle, here:

https://jsfiddle.net/r9pet266/6/

I wanted a slight delay between the mouse movement and the block movement, so I added a CSS transition property on the block.

The movement seems smooth as long as you click and drag inside the game div, but once you click outside the game div, clicking and dragging inside of it becomes very jumpy.

Does anybody know why?

HTML

<div id="outer">
  <div id="game"></div>
  <div id="instructions">
    1. Click and drag inside the red box --> smooth <br>
    2. Click on the green <br>
    3. Click and drag inside the red box --> jumpy
  </div>
</div>

CSS

#outer {
  height: 500px;
  background: green;
}

#instructions {
  position: absolute;
  top: 350px;
  left: 100px;
}

#game {
  position: relative;
  display: inline-block;
  width: 300px;
  height: 270px;
  background: red;
}

.block {
  transition: 100ms;
  position: absolute;
  width: 80px;
  height: 80px;
  background: black;
}

JavaScript :

var $block;

$('#game').mousedown(function (e) {
  e.preventDefault();

  $block = $('<div>');
  $block.addClass('block');
  updatePosition(e);
  $('#game').append($block);

  $('#game').mousemove(updatePosition);

  $(window).one('mouseup', function () {
    $block.remove();
    $('#game').off('mousemove');
  });
});

function updatePosition (e) {
  $block.css('top', e.pageY - 45 + 'px');
  $block.css('left', e.pageX - 45 + 'px');
}

When you move the cursor outside the red and black box, it's outside #game , so the mousemove event handler is not firing. You should assign mousemove event handler to document instead of #game , like this:

$(document).mousemove(updatePosition);

See updated JS Fiddle .

// change
$('#game').mousemove(updatePosition);
// to 
$(window).mousemove(updatePosition);

The reason why the block stops moving is that your mouseover event listener is only being run when you are moving over the red box.

The jumping is thanks to event bubbling . The black box is a child element of the red box, so hovering over the black box means you are also hovering over the red box. (Check out the link for a proper explanation.)

Solution:

$('#outer').mousedown(function (e) {
    e.preventDefault();
});

For whatever reason, canceling the default behavior on the green box stopped any jumpiness.

Updated fiddle:

https://jsfiddle.net/r9pet266/7/

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