因为公司项目有一个需求,要需要在一个div中去设置一个背景图片,并且还要再div中使用echarts画图,因此需要将一个div缩放以及拖动。
要实现以上功能,开起来好像有一点复杂,实际上很简单,创建两个div,只需要设置好子div的mousemove、mousedown、mouseup、mousewheel事件即可。
废话不多说直接上代码(复制过去即可用):
<!DOCTYPE html>
<html>
<body>
<div id="father" style="width: 600px; height: 600px; margin-left: auto;margin-right: auto;overflow: hidden;border: #000 solid 1px;">
<div id="showdiv" style="width:600px; height: 600px; background: url(test.png); background-size: 100% 100%;background-repeat: no-repeat;">
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js"></script>
<script>
// js代码
var old_x = 0;
var old_y = 0;
var leftkeydown = 0;
var old_offset = {left: 0, top: 0}
function listen_mousewheel(event, delta, deltaX, deltaY) {
var e = window.event || event
e.preventDefault()
var x_off = event.pageX - $(this).offset().left
var y_off = event.pageY - $(this).offset().top
var height = $(this).height()
var width = $(this).width()
var offset = $(this).offset()
if (delta == 1) {
var new_x = width * 1.1
var new_y = height * 1.1
} else {
var new_x = width * 0.9
var new_y = height * 0.9
}
$(this).height(new_y)
$(this).width(new_x)
$(this).offset({
left: offset.left + (x_off - (x_off / width * new_x)),
top: offset.top + (y_off - (y_off / height * new_y))
})
}
function listen_keydownmove(event) {
if (leftkeydown) {
var new_x = event.pageX - $(this).offset().left
var new_y = event.pageY - $(this).offset().top
$(this).offset({left: old_offset.left + (new_x - old_x), top: old_offset.top + (new_y - old_y)})
old_offset = $(this).offset()
}
}
function listen_mouseup(event) {
old_x = 0;
old_y = 0;
leftkeydown = 0;
old_offset = {left: 0, top: 0}
$(this).unbind('mousemove')
$(this).unbind('mouseup')
}
function listen_mousedown(event) {
if (event.button == 0) {
old_x = event.pageX - $(this).offset().left
old_y = event.pageY - $(this).offset().top
leftkeydown = 1;
old_offset = $(this).offset()
$(this).mousemove(listen_keydownmove)
$(this).mouseup(listen_mouseup)
}
}
$(function () {
$('#showdiv').mousewheel(listen_mousewheel)
$('#showdiv').mousedown(listen_mousedown)
})
</script>
</body>
</html>
效果图:
刚加载的图片 鼠标跟随放大后 鼠标选择移动后
网友评论