我正在创建一个图像滑块,当图像设置回屏幕的另一侧时,它不会继续移动



所以我的想法是,我每次点击向左移动 4 张图像 150px,当图像到达屏幕末尾时,它会到达另一侧,以便它可以重复圆圈。但是一旦图像实际出现在屏幕的右侧,它就会停止点击移动。

我的代码

'//菜单滑块的变量

var move = 150;
// MEAL ITEM SLIDER IMAGES 
var imgFood1 = document.getElementById('imgFood1')
var imgFood2 = document.getElementById('imgFood2')
var imgFood3 = document.getElementById('imgFood3')
var imgFood4 = document.getElementById('imgFood4')
imgFood1.style.position = "relative"
imgFood2.style.position = "relative"
imgFood3.style.position = "relative"
imgFood4.style.position = "relative"
function menuSlider(){
// GETTING THE POSITION OF THE IMAGES
var positionImg1 = imgFood1.getBoundingClientRect();
var positionImg2 = imgFood2.getBoundingClientRect();
var positionImg3 = imgFood3.getBoundingClientRect();
var positionImg4 = imgFood4.getBoundingClientRect();
// MOVING THE IMAGES 
imgFood1.style.right=move+"px"
imgFood2.style.right=move+"px"
imgFood3.style.right=move+"px"
if(positionImg4.left > 0 ) {
imgFood4.style.right=move+"px"
}else {
imgFood4.style.left="500px"
}
// INCREMENTING THE MOVE VALUE FOR THE NEXT FUNCTION CALL
move+=150
}
button.addEventListener("click", menuSlider);

'

你可以试试下面的代码。希望它适合您的情况。

var move = 150;
// MEAL ITEM SLIDER IMAGES
var imgFood1 = document.getElementById('imgFood1')
var imgFood2 = document.getElementById('imgFood2')
var imgFood3 = document.getElementById('imgFood3')
var imgFood4 = document.getElementById('imgFood4')
imgFood1.style.position = "absolute"
imgFood1.style.left = 0;
imgFood2.style.position = "absolute"
imgFood2.style.left = '150px';
imgFood3.style.position = "absolute"
imgFood3.style.left = '300px';
imgFood4.style.position = "absolute"
imgFood4.style.left = '450px';
function menuSlider(){
var arrayOfImages = [imgFood1,imgFood2,imgFood3,imgFood4];
for(let i = 0; i < arrayOfImages.length; i++) {
var positionImg = arrayOfImages[i].getBoundingClientRect();
var leftValue = parseInt(arrayOfImages[i].style.left);
if(positionImg.x < window.innerWidth) {
arrayOfImages[i].style.left = leftValue + move + "px"
}else {
arrayOfImages[i].style.left = '0px'
}
}
}
document.getElementById('myButton').addEventListener("click", menuSlider);
#myButton {
position: absolute;
top: 160px;
}
.images-container {
position: relative;
width: 100%;
height: 150px;
overflow: hidden;
}
<div class="images-container">
<img id="imgFood1" src="https://i.imgur.com/30XsebB.jpg" alt="cat" height="150" width="150"/>
<img id="imgFood2" src="https://i.imgur.com/30XsebB.jpg" alt="cat" height="150" width="150"/>
<img id="imgFood3" src="https://i.imgur.com/30XsebB.jpg" alt="cat" height="150" width="150"/>
<img id="imgFood4" src="https://i.imgur.com/30XsebB.jpg" alt="cat" height="150" width="150"/>
</div>
<button id="myButton" type="button" class="btn btn-default" data-dismiss="modal">Scroll</button>

最新更新