<!doctype html> <html> <head> <title></title> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.min.js"></script> <meta charset="utf-8" /> <style type="text/css"> body,html{ height:100%; } *{margin: 0;padding: 0;} .wrap{ width: 500px;height:100%; position: relative;margin: 0 auto;background: blue;transform: scale(0.8,0.8);} .box{ position: absolute;top:0;left:0; background: red;width: 200px;height: 200px; } </style> </head> <body> <div class="wrap"> <div class="box"></div> </div> <script type="text/javascript"> var element = $(".box") , e = $(".wrap"); var startX = 0, startY = 0, posY = 0, posX = 0; element.on("mousedown", function (event) { startX = event.clientX - element.offset().left; startY = event.clientY - element.offset().top; }); $(document).on("mousemove", function (event) { if (startX || startY) { posX = (event.clientX - e.offset().left) - startX; posY = (event.clientY - e.offset().top) - startY; element.css({ left: posX, top: posY }); } }); $(document).on("mouseup", function () { startX = 0; startY = 0; }); </script> </body> </html>
transform: scale(0.8,0.8)因为我加了css3属性缩放了。
怎么让它在缩放后 移动红框也正常啊?
直接复制代码本地运行就行
posX = (event.clientX - e.offset().left) - startX;
posY = (event.clientY - e.offset().top) - startY;
posX / 0.8
posY /0.8
element.css({ left: posX, top: posY });
或者
; (function ($) { $.extend($.fn, { getPos: function () { var target = this[0]; var left = target.offsetLeft; var top = target.offsetTop; var current = target.offsetParent; while (current) { left += current.offsetLeft; top += current.offsetTop; current = current.offsetParent; } return { left: left, top: top } } }) })($)
替换offset方法