框选的时候就可以拿到对角顶点,根据对角顶点就可以计算最大最小xy,然后相减就是宽高,下面有一个类似的案例,你可以参考下<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> html, body{ width: 100%; height: 100%; padding: 0; margin: 0; } #box{ width: 800px; height: 500px; background: #000; position: relative; } .item{ position: absolute; } .item.red{ border: 1px solid red; color: red } .item.blue{ border: 1px solid blue; color: blue } </style> </head> <body> <button class="drawBox" data-type="red">红色框</button> <button class="drawBox" data-type="blue">蓝色框</button> <button class="reset">清除</button> <button class="coords">坐标</button> <div id="box"></div> <div class="info"></div> </body> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script> let count = 0, sum = 0, activeType let $parent = $('#box'), $active, acx = 0, acy = 0, _left = 0, _top = 0; $('.drawBox').on('click', function(){ let type = $(this).attr('data-type') activeType = type bindEvent() }) function bindEvent(){ $parent.off('mousemove click') $parent.on('mousemove', function(e){ _left = e.offsetX _top = e.offsetY if($(e.target).hasClass('item')){ _left += parseInt(e.target.style.left) _top += parseInt(e.target.style.top) } $active && $active.css({ left: Math.min(acx, _left), top: Math.min(acy, _top), width: Math.abs(acx - _left), height: Math.abs(acy - _top) }) }).on('click', function(e){ count++ if(count == 1){ $active = $('<div class="item '+activeType+'"></div>') $parent.append($active) acx = e.offsetX acy = e.offsetY if($(e.target).hasClass('item')){ acx += parseInt(e.target.style.left) acy += parseInt(e.target.style.top) } }else{ $active.html(++sum) let width = Math.abs(acx - _left), height = Math.abs(acy - _top), minx = Math.min(acx, _left), maxx = Math.max(acx, _left), miny = Math.min(acy, _top), maxy = Math.max(acy, _top) let infoHtml = ` <p>盒子: ${sum}</p> <p>width: ${width}</p> <p>height: ${height}</p> <p>minx: ${minx}</p> <p>maxx: ${maxx}</p> <p>miny: ${miny}</p> <p>maxy: ${maxy}</p> ` $('.info').html(infoHtml) cancel() } }); } //重置 $('.reset').on('click', reset) function reset(){ sum = 0 $('#box .item').remove() clear() } function clear(){ isEdit = false $parent.off('mousemove click') $active && $active.remove() cancel() } function cancel(){ $active = null acx = acy = count = _left = _top = 0 } $('.coords').on('click', function(){ let res = [] $('#box .item').each(function(index, item){ res.push({ index: $(item).html(), x: parseFloat(item.style.left), y: parseFloat(item.style.top) }) }) console.log(res) }) </script> </html>
框选的时候就可以拿到对角顶点,根据对角顶点就可以计算最大最小xy,然后相减就是宽高,下面有一个类似的案例,你可以参考下