未封装函数
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>侧边栏案例</title><style>*{margin: 0;padding: 0;}body{position: relative;}#box{width: 200px;height: 200px;background: pink;position: absolute;top: 50px;left: -200px;}#box span{position: absolute;right: -20px;top: 70px;width: 20px;height: 45px;background-color: red;}</style></head><body><div id="box"><span id="btn">拉伸</span></div><script>// 1,获取事件源var box = document.getElementById('box')var btn = document.getElementById('btn')var timer = null// 2,通过鼠标悬浮在span标签设置事件btn.onmouseover = function () {// 为了防止定时器重叠生效,每次悬浮都要先清除定时器clearInterval(timer)// 2.1设置定时器,改变left值发生移动timer = setInterval(function () {// 2.2if判断如果盒子边框左边框距离父级定位盒子left值为0停止滑动if (box.offsetLeft === 0){clearInterval(timer)}else{box.style.left = box.offsetLeft + 10 + 'px'}},30)}// 鼠标离开btn.onmouseout = function () {// 为了防止定时器重叠生效,每次悬浮都要先清除定时器clearInterval(timer)// 2.1设置定时器,改变left值发生移动timer = setInterval(function () {// 2.2if判断如果盒子边框左边框距离父级定位盒子left值为-200px停止滑动if (box.offsetLeft === -200){clearInterval(timer)}else{box.style.left = box.offsetLeft - 10 + 'px'}},30)}</script></body></html>
封装函数代码
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>侧边栏案例</title><style>*{margin: 0;padding: 0;}body{position: relative;}#box{width: 200px;height: 200px;background: pink;position: absolute;top: 50px;left: -200px;}#box span{position: absolute;right: -30px;top: 70px;width: 30px;height: 60px;background-color: red;}</style></head><body><div id="box"><span id="btn">拉伸</span></div><script>// 1,获取事件源var box = document.getElementById('box')var btn = document.getElementById('btn')var timer = null// 2,通过鼠标悬浮在span标签设置事件box.onmouseover = function () {sport(box,0)}// 鼠标离开box.onmouseout = function () {sport(box,-200)}// 函数封装实现逻辑,传递运动盒子的事件源box,传递停止滑动的相对位移值function sport(boxname,value) {// 为了防止定时器重叠生效,每次悬浮都要先清除定时器// 如果value值为0需要+10px,反之-200的话需要-10pxvar leftValue = value == 0 ? 10 : -10clearInterval(timer)// 2.1设置定时器,改变left值发生移动timer = setInterval(function () {// 2.2if判断如果盒子边框左边框距离父级定位盒子left值为-200px停止滑动if (boxname.offsetLeft === value){clearInterval(timer)}else{// 接收到参数value,跟据value值判断加或减boxname.style.left = boxname.offsetLeft +leftValue + 'px'}},30)}</script></body></html>