js实现div的拖动放大缩小
效果
js实现div的拖动放大缩小
code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
#mapwrap {
width: 1000px;
height: 900px;
border: green solid 1px;
margin: 0 auto;
position: relative;
overflow: hidden;
transform: translate(0);
cursor: pointer;
z-index: 5;
overflow: hidden;
}
#mapImg {
width: 800px;
height: 511px;
border: 1px solid green;
/* background-image: url('img/mayi.jpeg'); */
/* background-repeat: no-repeat; */
position: absolute;
top: 0;
left: 0;
z-index: 3;
zoom: 100%;
}
#mapImg img {
width: 100%;
height: 100%;
z-index: 0;
-webkit-user-drag: none;
}
#rect {
width: 80px;
height: 80px;
z-index: 8;
border: 1px solid red;
position: absolute;
top: 219px;
left: 350px;
}
</style>
</head>
<body>
<div id="mapwrap">
<div id="mapImg">
<img src="img/mayi.jpeg" />
</div>
<div id="rect">
</div>
</body>
<script>
// import MySizeChange from './test'
var mapwrap = document.getElementById('mapwrap')
var mapImage = document.getElementById('mapImg')
var rect = document.getElementById('rect')
function MySizeChange(obj, w, h, x, y) {
this.x = x;
this.y = y;
this.preWidth = w;
this.preHeight = h;
this.obj = obj
this.down = false
this.pressX = 0
this.pressY = 0
this.onMouseWheel = function (e) {
let width = parseInt(this.obj.style.width, 10) || w;
var delta = Math.round(e.wheelDelta);
width += delta;
// console.log(width);
if (width > w) {
let k = width / this.preWidth //缩放倍数
obj.style.width = width + 'px'
this.preWidth = width //保存上一次宽度
let height = Math.round(this.preHeight * k)
//本次
this.obj.style.height = height + 'px'
this.preHeight = height
let deltaX = Math.round(width * (k - 1) / 2)
let deltaY = Math.round(height * (k - 1) / 2)
this.x = this.x - deltaX
this.y = this.y - deltaY
this.obj.style.left = this.x + 'px'
this.obj.style.top = this.y + 'px'
//减少到800 还原
} else {
this.obj.style.width = w + 'px'
this.obj.style.height = h + 'px'
this.obj.style.top = y + 'px'
this.obj.style.left = x + 'px'
this.x = x, this.y = y
}
}
this.onMouseDown = function (e) {
// console.log(e);
this.down = true
this.pressX = e.layerX
this.pressY = e.layerY
}
this.onMouseMove = function (e) {
if (this.down) {
let offsetX = e.layerX - this.pressX
let offsetY = e.layerY - this.pressY
this.x = this.x + offsetX
this.y = this.y + offsetY
this.obj.style.left = this.x + 'px'
this.obj.style.top = this.y + 'px'
}
}
this.onMouseUp = function (e) {
this.down = false
}
}
var obj = new MySizeChange(mapImage, 800, 511, 0, 0)
var obj1 = new MySizeChange(rect, 350, 219, 0, 0)
mapImage.onmousedown = function (e) {
obj.onMouseDown(e)
obj1.onMouseDown(e)
}
mapImage.onmousemove = function (e) {
obj.onMouseMove(e)
obj1.onMouseMove(e)
}
mapImage.onmouseup = function (e) {
obj.onMouseUp(e)
obj1.onMouseUp(e)
}
mapImage.onmousewheel = function (e) {
obj.onMouseWheel(e)
}
</script>
</html>
用到的图片: