rotating div with mouse move

后端 未结 3 1854
天涯浪人
天涯浪人 2021-01-18 03:38

I have the following code to rotate a div. By mousedown event on the image in the upper-right corner of the same div. I want the div to rotate till mouse up. logically I bel

相关标签:
3条回答
  • 2021-01-18 03:53

    I think this stack overflow question answers your question How to get mouseup to fire once mousemove complete

    The trick is to "ecapsulate" the mousemove and mouseup events in the mousedown event.

    0 讨论(0)
  • 2021-01-18 04:13

    There is a lib for this. Works standalone or as jQuery plugin https://github.com/PixelsCommander/Propeller

    0 讨论(0)
  • 2021-01-18 04:18

    I think the problem was that when the native drag event (that dragged the image) was fired (on mouse down) it was preventing the mouse up event to be fired. So you just need to prevent the default action of the mouse down event.

    Here you have a working example:

    HTML:

    <div class="drop">
        <div>
            <img src="http://www.belugerinstudios.com/image/picturethumbnail/FunnyCatFootballIcon.JPG"/>
        </div>
    </div>​
    

    Javascript:

    $(document).ready(function() {
      // the same as yours.
      function rotateOnMouse(e, pw) {
          var offset = pw.offset();
          var center_x = (offset.left) + ($(pw).width() / 2);
          var center_y = (offset.top) + ($(pw).height() / 2);
          var mouse_x = e.pageX;
          var mouse_y = e.pageY;
          var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
          var degree = (radians * (180 / Math.PI) * -1) + 100;
          //            window.console.log("de="+degree+","+radians);
          $(pw).css('-moz-transform', 'rotate(' + degree + 'deg)');
          $(pw).css('-webkit-transform', 'rotate(' + degree + 'deg)');
          $(pw).css('-o-transform', 'rotate(' + degree + 'deg)');
          $(pw).css('-ms-transform', 'rotate(' + degree + 'deg)');
      }
    
      $('.drop div img').mousedown(function(e) {
        e.preventDefault(); // prevents the dragging of the image.
        $(document).bind('mousemove.rotateImg', function(e2) {
          rotateOnMouse(e2, $('.drop div img'));
        });
      });
    
      $(document).mouseup(function(e) {
        $(document).unbind('mousemove.rotateImg');
      });
    });
    

    Demo: http://jsfiddle.net/rwBku/13/

    I have used jquery's namespaced events so you can unbind only the mousemove event that you want to.

    Please note that the rotation of the image is buggy, but I really didn't look at that method.

    0 讨论(0)
提交回复
热议问题