JS滑动条
setTimeout() 人气:0在完成这个案例之前需要看一下这个博客:JS案例-添加缓动画
这个案例会用到上面博客的缓动画函数。实现效果如下:
完整代码如下:
html代码:
<!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>滑动条案例</title> <style> body { overflow-x: hidden; } .slidebar { position: absolute; top: 500px; right: 0; width: 40px; height: 40px; text-align: center; line-height: 40px; cursor: pointer; color: #fff; background-color: #891383; } .con { position: absolute; left: 0; top: 0; width: 200px; height: 40px; background-color: #891383; color: #fff; text-align: center; line-height: 40px; z-index: -1; } </style> <script src="../js/index.js"></script> </head> <body> <div class="slidebar"> <span>⬅</span> <div class="con">问题反馈</div> </div> <script> // 获取元素 var slide = document.querySelector('.slidebar') var span = document.querySelector('span'); var con = document.querySelector('.con'); slide.addEventListener('mouseenter', function() { // 当动画执行完毕就把左箭头改为右箭头 moves(con, -160, function() { slide.children[0].innerHTML = '➡' }) }); slide.addEventListener('mouseleave', function() { // 当动画执行完毕就把右箭头又变为左箭头 moves(con, 0, function() { slide.children[0].innerHTML = '⬅' }) }) </script> </body> </html>
JS代码:
function moves(obj, target, callback) { clearInterval(obj.timer); obj.timer = setInterval(function() { // 把步长值改为整数,不要出现小数的情况 往上取整 var step = (target - obj.offsetLeft) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); // 回调函数写在清除定时器里面 这里只能写等于 if (obj.offsetLeft == target) { clearInterval(obj.timer); if (callback) { callback(); } } obj.style.left = obj.offsetLeft + step + 'px'; // console.log(obj.style.left); }, 15); }
加载全部内容