<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.cutarea {
width: 280px;
height: 180px;
margin: 100px auto;
position: relative;
}
img {
width: 100%;
height: 100%;
}
.mask {
position: absolute;
width: 100%;
height: 100%;
background: rgba(5, 99, 133, .6);
top: 0;
left: 0;
}
.box {
position: absolute;
left: 0;
top: 0;
width: 50px;
height: 50px;
background: url(**图片地址**) no-repeat;
}
.dot {
position: absolute;
width: 10px;
height: 10px;
bottom: -5px;
right: -5px;
background-color: red;
border-radius: 50%;
}
</style>
</head>
<body>
<div id="cutarea" class="cutarea">
<img src="**图片地址**">
<div class="mask"></div>
<div id="box" class="box">
<div id="dot" class="dot"></div>
</div>
</div>
<script>
**// 获取元素**
var dot = document.getElementById("dot");
var box = document.getElementById("box");
var cutarea = document.getElementById("cutarea");
**// 绑定事件**
dot.onmousedown = function (e) {
e.stopPropagation();
**// 获取鼠标位置**
var mouseX = e.clientX;
var mouseY = e.clientY;
**// 获取box宽高**
var width = box.clientWidth;
var height = box.clientHeight;
**// 为了扩大范围 给document绑定这个事件**
document.onmousemove = function (e) {
**// 获取鼠标移动后的位置**
var movedX = e.clientX;
var movedY = e.clientY;
**// 计算宽度**
var resultWidth = movedX - mouseX + width;
var resultHeight = movedY - mouseY + height;
if (resultWidth < 50) {
resultWidth = 50;
} else if (resultWidth >= cutarea.clientWidth - box.offsetLeft) {
resultWidth = cutarea.clientWidth - box.offsetLeft
}
if (resultHeight < 50) {
resultHeight = 50;
} else if (resultHeight >= cutarea.clientHeight - box.offsetTop) {
resultHeight = cutarea.clientHeight - box.offsetTop
}
**// 赋值**
box.style.width = resultWidth + "px";
box.style.height = resultHeight + "px";
}
}
box.onmousedown = function (e) {
**// 获取鼠标位置**
var mouseX = e.clientX;
var mouseY = e.clientY;
**// 获取box定位值**
var left = box.offsetLeft;
var top = box.offsetTop;
document.onmousemove = function (e) {
**// 获取鼠标移动后的位置**
var movedX = e.clientX;
var movedY = e.clientY;
**// 计算结果定位值**
var resultLeft = movedX - mouseX + left;
var resultTop = movedY - mouseY + top;
**// 判定**
if (resultLeft < 0) {
resultLeft = 0;
} else if (resultLeft > cutarea.clientWidth - box.clientWidth) {
resultLeft = cutarea.clientWidth - box.clientWidth;
}
if (resultTop < 0) {
resultTop = 0;
} else if (resultTop > cutarea.clientHeight - box.clientHeight) {
resultTop = cutarea.clientHeight - box.clientHeight;
}
box.style.left = resultLeft + "px";
box.style.top = resultTop + "px"
box.style.backgroundPositionX = -resultLeft + "px";
box.style.backgroundPositionY = -resultTop + 'px';
}
}
document.onmouseup = function () {
document.onmousemove = null;
}
document.onselectstart = function() {
return false;
}
</script>
</body>
</html>
区域内拖拽、放大,显示覆盖图片(不考虑兼容)
最新推荐文章于 2022-07-01 11:38:43 发布