底下有完整代码。
1.让图片在容器内可拖动
$("#draggable-image").draggable({
// containment: "#image-container"
});
2.监听滚轮事件
// event.wheelDelta>0 用来判断滚轮是上滚动还是下滚动
$("img").bind("mousewheel",
function(e) {
zoomImg(this,e.clientX,e.clientY);
return false;
});
3.使图片在焦点位置缩放
(clientX-o.offsetLeft)/oWidth : 鼠标在容器内的位置,减去图片在容器内的位置,即可得到鼠标在图片内的位置(即焦点位置)。 除以图片的宽度,即可得到鼠标在图片内的百分比位置
(oWidth + size): 这是图片缩放后的大小,乘以鼠标在图片内的百分比,得到缩放后的焦点位置。再减去缩放前的焦点位置,即可得到缩放前后的焦点偏移距离。
position.left: 图片在容器内的定位,减去缩放前后的焦点偏移距离,即可让图片焦点缩放。
var position = img.position();
img.css({
left: position.left - Math.round((clientX-o.offsetLeft)/oWidth * (oWidth + size) - (clientX-o.offsetLeft)),
top: position.top - Math.round((clientY-o.offsetTop)/oHeight * (oHeight + size / oWidth * oHeight) - (clientY-o.offsetTop))
})
原来的尺寸加缩放的尺寸,再赋值图片的宽高。即可使图片缩放
img.width(oWidth + size);
img.height(oHeight + size / oWidth * oHeight);
<body>
<script type="text/javascript">
var fileUpLoadUrl = window.localStorage.getItem('fileUpLoadUrl');
$(function() {
$("#draggable-image").draggable({
// containment: "#image-container"
});
$("img").bind("mousewheel",
function(e) {
zoomImg(this,e.clientX,e.clientY);
return false;
});
});
//缩放
function zoomImg(o,clientX,clientY) {
// event.wheelDelta>0 用来判断滚轮是上滚动还是下滚动
var size = event.wheelDelta>0?70:-70; //滚轮每次滚动,图片缩放的尺寸
var img = $(o);
var oWidth = img.width(); //取得图片的实际宽度
var oHeight = img.height(); //取得图片的实际高度
//当图片宽高到一定尺寸,就不能继续缩小了
if((oWidth<90||oHeight<90)&&size<0){
return
}
//使图片在焦点位置缩放
// ((clientX-o.offsetLeft)/oWidth * (oWidth + size))
// (clientY-o.offsetTop)/oHeight * (oHeight + size / oWidth * oHeight)
var position = img.position();
img.css({
left: position.left - Math.round((clientX-o.offsetLeft)/oWidth * (oWidth + size) - (clientX-o.offsetLeft)),
top: position.top - Math.round((clientY-o.offsetTop)/oHeight * (oHeight + size / oWidth * oHeight) - (clientY-o.offsetTop))
})
//图片尺寸变化
img.width(oWidth + size);
img.height(oHeight + size / oWidth * oHeight);
}
</script>
<div id="image-container" >
<img alt="example" id="draggable-image" style="width: 1200px;height: 700px;" class="image draggable" src="https://www.baidu.com/img/flexible/logo/pc/result.png" />
</div>
</body>