如何使用jQuery将可拖拽元素居中放置在image-map图片映射的可投放区域
解决方案
实现思路
- 给外层容器设置相对定位,拖拽元素设置绝对定位,所有位置计算基于图片容器的相对坐标,避免页面布局变动导致定位偏移
- 投放命中目标区域后,读取对应
<area>标签的坐标和形状属性,计算区域的中心点坐标 - 结合拖拽元素自身的宽高做偏移修正,让元素完全居中落在目标区域内
- 兼容多边形、矩形两种常见的image-map形状
调整后代码
HTML
<div style="border: 1px solid red;" class="ui-widget-header"> <!-- 给container加相对定位 --> <div id="container" style="position: relative;"> <img id="mainSectorBet" class="mainSectorBet" src="你的轮盘图片本地路径" usemap="#image-map"> <map name="image-map" id="my-image-map"> <area id="nula" target="" alt="P0" title="P0" href="" coords="82,230,82,1,45,17,10,71,1,117,12,166,45,213" shape="poly"> <area id="C1" target="" alt="C1" title="C1" href="" coords="151,142,177,164" shape="rect"> </map> </div> <!-- 给拖拽元素加绝对定位、固定宽高,宽高可根据业务需求调整 --> <div id="draggable" class="divar" style="position: absolute;width: 30px;height: 30px;background: blue;"></div> </div>
jQuery
$(function () { $('#mainSectorBet').mapster({ mapKey: "alt", fillOpacity: 0.8, fillColor: 'ff0000', stroke: true, strokeWeight: 2, strokeColor: '00ff00', onConfigured: function() { $('#mainSectorBet').siblings().css('z-index', 0); $('#mainSectorBet').css('z-index', 10); } }).parent().css({"display":"flex", "justify-content":"center", "align-items": "center"}); $(".divar" ).css('z-index', 5).draggable({ opacity: "0.5", cursor: "grabbing", revert: 'invalid', drag: function(){ $(this).css('z-index', 5) } }); $("#mainSectorBet").droppable({ drop: function(event, ui) { var landingAlt = $('#mainSectorBet').mapster('highlight'); if(!landingAlt) return; // 找到命中的area元素 const $targetArea = $(`area[alt="${landingAlt}"]`); const coords = $targetArea.attr('coords').split(',').map(Number); const shape = $targetArea.attr('shape'); let centerX, centerY; // 根据形状计算中心点 if(shape === 'rect') { // 矩形坐标格式:x1,y1,x2,y2 centerX = (coords[0] + coords[2]) / 2; centerY = (coords[1] + coords[3]) / 2; } else if(shape === 'poly') { // 多边形取所有x坐标的平均值、y坐标的平均值作为中心点 const xList = coords.filter((_, index) => index % 2 === 0); const yList = coords.filter((_, index) => index % 2 === 1); centerX = xList.reduce((a,b) => a + b, 0) / xList.length; centerY = yList.reduce((a,b) => a + b, 0) / yList.length; } // 计算拖拽元素的偏移,让元素中心和区域中心重合 const $draggable = ui.draggable; const dragWidth = $draggable.outerWidth(); const dragHeight = $draggable.outerHeight(); const imgOffset = $('#mainSectorBet').position(); // 设置最终位置 $draggable.css({ left: imgOffset.left + centerX - dragWidth / 2 + 'px', top: imgOffset.top + centerY - dragHeight / 2 + 'px', zIndex: 20 }); } }); })
注意事项
- 如果轮盘图片有响应式缩放需求,计算坐标时需要额外乘以图片的缩放比例,否则会出现定位偏移
- 如果需要支持多元素同时投放,可以在投放逻辑中新增克隆拖拽元素的逻辑,避免同一个元素反复移动
内容的提问来源于stack exchange,提问作者Antonio Klepo
相关产品推荐
相关产品推荐

