<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<meta name="keywords" content="关键词">
<meta name="description" content="描述">
<meta name="author" content="">
<style>
* {
margin: 0;
padding: 0;
}
body {
user-select: none;
}
.content {
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
width: 320px;
height: 207px;
margin: auto;
}
.content ul {
list-style-type: none;
}
.content ul li {
position: absolute;
}
.content ul li img {
display: block;
width: 300px;
border: 10px solid #958a0d;
cursor: pointer;
}
</style>
</head>
<body>
<div class="content">
<ul>
<li><img src="images/1.jpg" alt=""></li>
<li><img src="images/2.jpg" alt=""></li>
<li><img src="images/3.jpg" alt=""></li>
<li><img src="images/4.jpg" alt=""></li>
<li><img src="images/5.jpg" alt=""></li>
</ul>
</div>
<script>
// 获取元素
let oCon = document.querySelector('.content')
let aLi = [...document.getElementsByTagName('li')];
//定义一些其他变量
let zIndex = 0;
let winW, winH, leftMax, topMax;
//获取拖拽元素的宽高
let w = oCon.clientWidth;
let h = oCon.clientHeight;
//封装一个计算最大值和最小值的函数
function ltMax() {
let wObj = getViewportOffset();
winW = wObj.w;
winH = wObj.h;
leftMax = (winW - w) / 2;
topMax = (winH - h) / 2;
}
ltMax()
window.onresize = ltMax;//浏览器窗口发生变化就触发window.onresize
//封装获取浏览器屏幕的宽高
function getViewportOffset() {
if (window.innerWidth) {//主流浏览器
return {
w: window.innerWidth,
h: window.innerHeight
}
} else {
if (document.compatMode === 'CSS1Compat') {
return {//标准盒模型
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
}
} else {//怪异盒模型
return {
w: document.body.clientWidth,
h: document.body.clientHeight
}
}
}
}
//批量绑定事件
aLi.forEach((oLi, index) => {
oLi.onmousedown = function (ev) {//给每个oLi绑定事件onmousedown事件,并拿到事件对象ev
ev = ev || window.event//兼容
ev.preventDefault()//图片默认带拖拽残影行为,清除默认
//获取鼠标按下时距离浏览器左侧和顶部的距离
let startX = ev.clientX;
let startY = ev.clientY;
//获取被拖拽的li元素距离浏览器左侧,顶部距离
let startL = this.offsetLeft;
let startT = this.offsetTop;
// let This = this;//外侧定义This,在内存使用,也可以采用强制绑定外侧this,不定义This
//绑定鼠标移动事件,绑定到document上,保证只要鼠标在页面上,事件始终会执行
document.onmousemove = function (ev) {
ev = ev || window.event//兼容
//获取鼠标移动后的距离
let nowX = ev.clientX;
let nowY = ev.clientY;
//计算容器的偏移
let nowL = nowX - startX + startL;
let nowT = nowY - startY + startT;
//边界检测
nowL = Math.max(nowL, -leftMax)//水平
nowL = Math.min(nowL, leftMax)
nowT = Math.max(nowT, -topMax)//垂直
nowT = Math.min(nowT, topMax)
//给元素设置新的位置
// This.style.top = nowT + 'px';//使用外部This
// This.style.left = nowL + 'px';
// This.style.zIndex = ++zIndex;//谁被点击谁的zIndex就加加
this.style.top = nowT + 'px';//强制绑定外部this方法.bind(this)
this.style.left = nowL + 'px';
this.style.zIndex = ++zIndex;
}.bind(this)
//解绑事件
document.onmouseup = function (ev) {
this.onmousemove = null;
this.onmouseup = null;
}
}
});
</script>
</body>
</html>
网友评论