dragresize.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. $(function () {
  2. window.dragresize = true
  3. var dragging
  4. var lastx
  5. var lasty
  6. var dragsizew
  7. var dragsizeh
  8. var minw
  9. var minh
  10. var maxw
  11. var maxh
  12. $(document).on('dblclick', '.dragresize', function (e) {
  13. var target = $(e.target)
  14. target.toggleClass('full')
  15. if (target.hasClass('full')) {
  16. target.addClass('dragged')
  17. target.width(e.target.naturalWidth)
  18. target.height(e.target.naturalHeight)
  19. } else {
  20. target.removeClass('dragged')
  21. target.width('auto')
  22. target.height('auto')
  23. }
  24. })
  25. var MIN_WIDTH_PX = 100
  26. var MAX_WIDTH_RATIO = 100
  27. $(document).on('mousedown', '.dragresize', function (e) {
  28. if (e.which && e.which != 1) {
  29. return
  30. }
  31. e.preventDefault();
  32. dragging = $(e.target)
  33. dragging.addClass('dragging')
  34. dragsizew = e.target.naturalWidth
  35. dragsizeh = e.target.naturalHeight
  36. if (dragsizew > dragsizeh) {
  37. minw = MIN_WIDTH_PX
  38. minh = MIN_WIDTH_PX * (dragsizeh / dragsizew)
  39. maxw = dragsizew * MAX_WIDTH_RATIO
  40. maxh = (dragsizew * MAX_WIDTH_RATIO) * (dragsizeh / dragsizew)
  41. } else {
  42. minh = MIN_WIDTH_PX
  43. minw = MIN_WIDTH_PX * (dragsizew / dragsizeh)
  44. maxh = dragsizeh * MAX_WIDTH_RATIO
  45. maxw = (dragsizeh * MAX_WIDTH_RATIO) * (dragsizew / dragsizeh)
  46. }
  47. lastx = e.clientX
  48. lasty = e.clientY
  49. })
  50. $(document).on('mousemove', function (e) {
  51. if (!dragging) {
  52. return
  53. }
  54. var px = e.clientX
  55. var py = e.clientY
  56. var newx = px - lastx
  57. var newy = py - lasty
  58. if (Math.abs(newx) < 1 && Math.abs(newy) < 1) {
  59. return;
  60. }
  61. e.preventDefault();
  62. var width = dragging.width()
  63. var height = dragging.height()
  64. dragging.addClass('dragged')
  65. if (Math.abs(newx) > Math.abs(newy)) {
  66. dragging.css({ 'width': Math.min(maxw, Math.max(width + (width * (.0025 * newx)), minw)) + 'px', 'height': 'auto' })
  67. } else {
  68. dragging.css({ 'height': Math.min(maxh, Math.max(height + (height * (.0025 * newy)), minh)) + 'px', 'width': 'auto' })
  69. }
  70. lastx = px
  71. lasty = py
  72. })
  73. $(document).on('mouseup', function (e) {
  74. if (!dragging) {
  75. return
  76. }
  77. dragging.removeClass('dragging')
  78. dragging = undefined
  79. });
  80. })