最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
JavaScript实现橱窗展示效果代码示例
时间:2021-11-08 编辑:袖梨 来源:一聚教程网
本篇文章小编给大家分享一下JavaScript实现橱窗展示效果代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。
1.先搭架子
css;">* { margin: 0; padding: 0; } .box { border: 1px solid #000; margin: 100px auto; } ul { list-style: none; display: flex; } ul img { vertical-align: top; } .progress { width: 100%; background: #ccc; } .progress>.line { height: 100%; background: orange; border-radius: 15px; }
2.逻辑部分
拿到需要操作的元素
计算ul的宽度
设置ul的宽度
计算滚动条的宽度
设置滚动条的宽度
监听鼠标按下的事件
拿到滚动条当前的位置
拿到鼠标在滚动条中按下的位置
监听鼠标移动事件
拿到鼠标在滚动条中移动之后的位置
计算偏移位
安全校验
重新设置滚动条的位置
计算图片的滚动距离
重新设置图片的位置
.box { overflow: hidden; } ul { position: relative; } .progress { position: relative; } .progress>.line { position: absolute; left: 0; top: 0; }
//1.拿到需要操作的元素 const oUl = document.querySelector("ul"); const oItems = oUl.querySelectorAll("li"); const oProgress = document.querySelector(".progress"); const oLine = document.querySelector(".line"); const oBox = document.querySelector(".box"); //2.计算ul的宽度 const ulWidth = oItems[0].offsetWidth * oItems.length; //3.设置ul的宽度 oUl.style.px'; //4.计算滚动条的宽度 // 滚动条的宽度/滚动条滚动范围 = 容器的宽度/内容的范围 const progressWidth = oProgress.offsetWidth; const boxWidth = oBox.offsetWidth; const lineWidth = boxWidth / ulWidth * progressWidth; //5.设置滚动条的宽度 oLine.style.px'; // 计算滚动条最大能够滚动的范围 const maxLineX = progressWidth - lineWidth; // 计算图片最大能够滚动的范围 const maxImgX = boxWidth - ulWidth; //6.监听鼠标按下的事件 oLine.onmousedown = function(e) { e = e || window.e; //a.拿到滚动条当前的位置 let begin = parseFloat(oLine.style.left) || 0; //b.拿到鼠标在滚动条中按下的位置 let mouseX = e.pageX - oBox.offsetLeft; //7.监听鼠标移动事件 oLine.onmousemove = function(e) { e = e || window.e; //c.拿到鼠标在滚动条中移动之后的位置 let moveMouseX = e.pageX - oBox.offsetLeft; //d.计算偏移位 let offsetX = moveMouseX - mouseX + begin; //e.安全校验 offsetX = offsetX < 0 ? 0 : offsetX; offsetX = offsetX > maxLineX ? maxLineX : offsetX; //f.重新设置滚动条的位置 oLine.style.left = offsetX + 'px'; //g.计算图片的滚动距离 // 滚动条滚动的距离 / 滚动条最大能够滚动的范围 = 图片滚动的距离 / 图片最大能够滚动的范围 // 滚动条滚动的距离 / 滚动条最大能够滚动的范围 * 图片最大能够滚动的范围 = 图片滚动的距离 const imgOffsetX = offsetX / maxLineX * maxImgX; // h.重新设置图片的位置 oUl.style.left = imgOffsetX + "px"; }; }; document.onmouseup = function() { oLine.onmousemove = null; }
-
上一个: Java虚拟机栈jvm栈的作用代码示例
相关文章
- SpringBoot测试配置属性与web启动环境解析 10-24
- vue中将el-switch值true、false改为number类型的1和0解析 10-24
- Vue中的路由配置项meta使用解读 10-24
- SpringBoot自定义bean绑定解析 10-24
- SpringBoot常用计量与bean属性校验和进制数据转换规则解析 10-24
- 工厂方法在Spring框架中的运用介绍 10-24