最近项目中完成的需求,仿百度地图中的功能:
要求:1.底层图可以拖拽、缩放。
2.拖拽一个图标,在底层图上对应位置添加一个标注点,该标注点位置要随底层图移动。
3.添加的标注点,可以拖动,删除。
主要知识点和难点就是各个浏览器的点击、拖拽、缩放事件兼容性,对js运动属性、运动偏移位置的了解,以及js面向对象的应用。
这里跟大家分享一下完成后的代码。
html代码主要知识点就是运动元素和底层元素的相对绝对定位,css代码不再贴出:
<div id="warp" style="position: relative;width: 100%;height: 100%;background: #d7d7d7;">
<img title="拖动" class="dragImg" id="dragImg" src="images/video_16px_566474.png">
<div class="dragAble bgDiv" id="block1" style="zoom:1;">
<img id="wheelImg" src="images/photo2FDIB963M30AI20009NOS.jpg" style="zoom:1;" title="底层图片">
<p>这段文字跟着div一起运动</p>
</div>
</div>
js代码,初始化:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 var clearSlct = "getSelection" in window ? function() { 2 window.getSelection().removeAllRanges(); 3 } : function() { 4 document.selection.empty(); 5 }; 6 $(window).on("mouseup keyup", function() { 7 clearSlct(); 8 }); 9 document.getElementById('warp').oncontextmenu = function(e){ 10 e.preventDefault(); 11 }; 12 var dragDemo=new dragImg('block1','dragImg','wheelImg');
js代码,构造器+原型链进行面向对象开发:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
function dragImg(bgDivId, imgId, bgImgId) { this.disX = 0; this.disY = 0; //初始点击点 this.xx = 0; this.yy = 0; //点击点相对于button的左上角的距离left,top this.marginX = 0; this.marginY = 0; //运动后底层图偏移量 this.isdrag = false; this.clicky = 0; this.clickx = 0; //初始点击点 this.oDragObj = null; //操作对象 this.init(bgDivId, imgId); this.initBgDiv(bgDivId); this.initMouseWheel(bgImgId); } dragImg.prototype = { init: function(bgDivId, imgId) { //图标拖拽 dragImg.imgId