JS实现简单的图片拖拽和缩放功能

工作需要,写了个简单的图片拖拽和缩放功能,有需要的可以参考一下

拖拽:(拖拽目标需要做定位,并设置draggable=“false”)

popupDrag: function(ev){
    var ev = ev || event;
    var obj = document.getElementById('img_li');
    var disX = ev.clientX - obj.offsetLeft
    var disY = ev.clientY - obj.offsetTop;
    if ( obj.setCapture ) {
        obj.setCapture();
    }
    document.onmousemove = function(ev) {
        var ev = ev || event;
        $(obj).css({
            'left' : ev.clientX  - disX + 'px',
            'top' : ev.clientY - disY + 'px',
            'right' : 'auto',
            'bottom' : 'auto'
        })
    }
    document.onmouseup = function() {
        document.onmousemove = document.onmouseup = null;
        //释放全局捕获 releaseCapture();
        if ( obj.releaseCapture ) {
            obj.releaseCapture();
        }
    }   
    return false;
};

缩放:(要用到mousewheel鼠标滚轮事件)

zoomimg: function(e){
    var ev = e || event;
    var obj = document.getElementById('img_li');
    var disX = ev.clientX - obj.offsetLeft;
    var disY = ev.clientY - obj.offsetTop;
    var changeZoom = 1;
    var scaleS  = 0;
    if (e.detail) {
        changeZoom += -(e.detail / 260);
    } else if (e.wheelDelta) {
        changeZoom += (e.wheelDelta / 880);
    }
    if (changeZoom < 0.8) { // 最小缩放 0.7
        changeZoom = 0.8;
    }
    changeZoom = parseInt(changeZoom * 10) / 10;
    scaleS *= changeZoom;
     $('#img_li').css({
         'transform' : 'scale('+ scaleS +')'
     })
};

你可能感兴趣的:(js)