// 渲染原始图片
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;
});
});
图片简单缩放及拖动
最新推荐文章于 2024-02-23 15:41:29 发布