不顾一切,我正在尝试创建一个普通的 JavaScript 轮播。 我有两个问题: 1. 图像按应有的 -680px 宽度向左移动,但当我尝试为右侧按钮创建相同的功能时,左侧值变为 1370px,使图片脱离屏幕。 2.我希望它向左滑动而不是向左跳(向右相同),我设法让它做到这一点,但它在第一张幻灯片上不起作用,只能从第二张幻灯片上起作用。 以下是轮播的 HTML 代码:
<div id = "container">
<div id = "carousel">
<div class = "slide"><img class = "slideImage" class = "active" src = "sithCover.png"></div>
<div class = "slide"><img class = "slideImage" src = "darthVader.png"></div>
<div class = "slide"><img class = "slideImage" src = "darthSidious.png"></div>
<div class = "slide"><img class = "slideImage" src = "kyloRen.png"></div>
</div>
</div>
<div id = "left" class = "button"></div>
<div id = "right" class = "button"></div>
这是 CSS 代码:
#container {
position: absolute;
top: 200px;
left: 100px;
width: 680px;
height: 360px;
white-space: nowrap;
overflow:hidden;
}
#carousel {
position: absolute;
width: 2740px;
height: 360px;
white-space: nowrap;
overflow: hidden;
transition: left 300ms linear;
}
.slide {
display: inline-block;
height: 360px;
width: 680px;
padding: 0;
margin: 0;
transition: left 300ms linear;
}
.slideImage {
position:relative;
height: 360px;
width: 680px;
float: left;
}
.button {
position: absolute;
top: 340px;
height: 60px;
width: 60px;
border-bottom: 12px solid red;
}
#left {
left: 115px;
border-left: 12px solid red;
transform: rotate(45deg);
}
#right {
left: 693px;
border-right: 12px solid red;
transform: rotate(-45deg);
}
这是 JavaScript:
var carousel = document.querySelector('#carousel');
var firstVal = 0;
document.querySelector('#left').addEventListener("click", moveLeft);
function moveLeft (){
firstVal +=685;
carousel.style.left = "-"+firstVal+"px";
};
document.querySelector('#right').addEventListener("click", moveRight);
function moveRight() {
firstVal +=685;
carousel.style.left = "+"+firstVal+"px";
};
这是一个 JSFiddle,以便您可以明白我的意思: “https://jsfiddle.net/way81/8to1kkyj/”
感谢您花时间阅读我的问题,我们将不胜感激。
最佳答案
当然,左键单击时它会从 -685px
开始,然后单击右键会变为 +1370px
;您总是将 685 添加到您的 firstVal
变量中。
firstVal = 0
//firstVal is worth 0
moveLeft()
//firstVal is now worth 685
moveRight()
//firstVal is now worth 1370.
问题是,当您将 firstVal
应用于 JavaScript 中的 CSS 内容时,您会创建一个字符串来获取负值(在 前面应用“-”号)第一个值
)
相反,像这样写
function moveLeft (){
firstVal -=685; //note we now subtract, the "-" should appear when the number becomes negative
carousel.style.left = firstVal + "px";
};
function moveRight() {
firstVal +=685;
carousel.style.left = firstVal + "px";
};
关于javascript - 修复普通 Javascript 轮播的右侧按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34857502/