图片简单缩放及拖动

// 渲染原始图片
let image = $('<img src="'+getRoot()+path+'" id="srcImg"/>');
$("#container").html(image);

// 添加鼠标滚轮控制图片放大缩小事件
$(image).on('complete load', function(){
	// 使图片定位居中
	let width = $(this).width();
    let height = $(this).height();
    let boxWidth = $(this).parent().width();
    let boxHeight = $(this).parent().height();
	let top = (boxWidth - width)/2;
	let left = (boxHeight - height)/2;
	$(this).css({
		'left': top+'px',
		'top': left+'px',
	});
	
	let scale = 1;
	// 监听鼠标滚轮控制图片缩放
	$(this).on("mousewheel DOMMouseScroll", function(e){
		var delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) ||  // chrome & ie
            			(e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1));        // firefox
	    if (delta > 0) {
			scale += 0.1;
	    } else if (delta < 0) {
	        scale -= 0.1;
	    }
		scale = Math.max(1, scale);
		$(this).css({'transform': 'scale('+scale+')'});
	});
	
	// 添加鼠标左键监听事件
	$(this).mousedown(function(e){
		e = e || window.event;
		// 阻止默认事件
	 	if(e.stopPropagation) e.stopPropagation();
    	if(e.preventDefault) e.preventDefault();
		e.cancelBubble=true;
		e.returnValue=false;
		
		if(e.which == 1){
			let _this = $(this);
			let top = parseInt($(_this).css("top"));
			let left = parseInt($(_this).css("left"));
			let startY = e.pageY - top;
			let startX = e.pageX - left;
			
			// 监听鼠标滑动事件
			$(this).css({'cursor': 'move'});
			$(document).mousemove(function(e) {
				e = e || window.event;
				if(!_this[0].contains(e.target)){
					return true;
				}
				// 获取鼠标的位移(鼠标此时的page值 - 鼠标按下时的初始值 = 元素的移动值)
		        let x = e.pageX - startX;
		        let y = e.pageY - startY;
				
				$(_this).css({
					'top': y+'px',
					'left': x+'px',
				});
		    }).mouseup(function() {
				$(this).unbind('mousemove');
        		$(this).unbind('mouseup');
				$(_this).css({'cursor': 'crosshair'});
			});
		}
		return false;
	});
});
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值