如何使用Javascript将图片移动指定像素距离
解决方案
问题根因
你当前的代码每次触发点击事件时,都会直接将所有.images元素的margin-left固定赋值为-300px,首次赋值生效后,后续重复点击写入的都是相同的属性值,元素位置不会发生变化,因此看不到持续移动的效果。
修改后可运行代码
<div class="container"> <div class="images"> <img src="https://images.unsplash.com/photo-1596536220655-21429cf12ae0?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80"/> </div> <div class="images"> <img src="https://images.unsplash.com/photo-1596536220655-21429cf12ae0?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80"/> </div> <div class="images"> <img src="https://images.unsplash.com/photo-1596536220655-21429cf12ae0?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80"/> </div> <div class="images"> <img src="https://images.unsplash.com/photo-1596536220655-21429cf12ae0?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80"/> </div> </div> <button id="moveIt">点击移动</button> <button id="autoMove">开启自动移动</button> <style> .container { display: flex; justify-content: space-around; overflow: hidden; max-width: 100%; z-index: 222; } .images { width: 300px !important; display: block; text-align: center; margin-right: 10px; height: 400px !important; transition: margin-left 0.3s ease; /* 新增过渡动画,移动更流畅 */ } </style> <script> let images = document.querySelectorAll('.images'); const moveBtn = document.getElementById('moveIt'); const autoMoveBtn = document.getElementById('autoMove'); // 新增累计位移变量 let offset = 0; const step = 310; // 300宽度+10的margin-right,刚好移动一张的位置 let moveHandler = () => { offset -= step; for(let i=0; i < images.length; i++) { images[i].style.marginLeft = offset + "px"; } } // 点击移动逻辑 moveBtn.addEventListener('click', moveHandler); // 自动移动逻辑 let autoTimer = null; autoMoveBtn.addEventListener('click', () => { if(autoTimer) { clearInterval(autoTimer); autoTimer = null; autoMoveBtn.innerText = '开启自动移动'; } else { autoTimer = setInterval(moveHandler, 2000); // 每2秒移动一次 autoMoveBtn.innerText = '停止自动移动'; } }) </script>
关键修改说明
- 新增
offset全局变量累计位移值,每次触发移动时叠加偏移量,保证每次赋值的margin-left都不同,实现持续移动 - 新增
transition属性给移动过程添加流畅动画 - 补充了自动轮播逻辑,通过
setInterval实现定时自动位移,符合你的最终需求,也可以替换为递归setTimeout实现相同效果 - 位移步长设置为310px,刚好匹配图片宽度+右边距的总宽度,每次移动刚好切换一张图片的位置
内容的提问来源于stack exchange,提问作者that_digital_dude
相关产品推荐
相关产品推荐

