Я хочу добавить кнопку в свой слайдер, я сделал это с помощью тега «a», но ее нельзя выбрать и она не работает как ссылка.
Я нашел этот код в сети, но я думаю, что этот код очень сложный, я не могу понять, где написать правильный код для кнопки.
Добавленная мной кнопка появляется только на первом слайде, однако мне нужно добавить кнопку на каждый слайд.
var slideIndex,slides,dots,captionText;
function initGallery(){
// 1 para ocultar y mostrar imageHolder con opasity 0
slideIndex = 0;
slides=document.getElementsByClassName("imageHolder"); // slides=4
slides[slideIndex].style.opacity=1;
// 2 para mostrar las letras
captionText=document.querySelector(".captionTextHolder .captionText");
captionText.innerText=slides[slideIndex].querySelector(".captionText").innerText;
// 3 disable nextPrevBtn if slide count is one
if (slides.length<2){
var nextPrevBtns=document.querySelector(".leftArrow,.rightArrow");
nextPrevBtns.style.display = "none";
for (i = 0; i < nextPrevBtn.length; i++) {
nextPrevBtn[i].style.display = "none";
}
}
// 4 add dots
dots=[];
var dotsContainer=document.getElementById("dotsContainer"),i;
for (i = 0; i < slides.length; i++) {
var dot=document.createElement("span");
dot.classList.add("dots");
dotsContainer.append(dot);
dot.setAttribute("onclick","moveSlide("+i+")");
dots.push(dot);
}
dots[slideIndex].classList.add("active");
}
// botones de izquierda y derecha
initGallery();
function plusSlides(n) {
moveSlide(slideIndex+n);
}
function moveSlide(n){
var i;
var current,next;
var moveSlideAnimClass = {
forCurrent:"",
forNext:""
};
var slideTextAnimClass;
if (n>slideIndex) {
if (n >= slides.length){n=0;}
moveSlideAnimClass.forCurrent = "moveLeftCurrentSlide";
moveSlideAnimClass.forNext = "moveLeftNextSlide";
slideTextAnimClass = "slideTextFromTop";
}else if (n<slideIndex){
if (n<0){n=slides.length-1;}
moveSlideAnimClass.forCurrent = "moveRightCurrentSlide";
moveSlideAnimClass.forNext = "moveRightPrevSlide";
slideTextAnimClass = "slideTextFromBottom";
}
if (n!=slideIndex){
next = slides[n];
current=slides[slideIndex];
for (i = 0; i < slides.length; i++) {
slides[i].className = "imageHolder";
slides[i].style.opacity=0;
dots[i].classList.remove("active");
}
current.classList.add(moveSlideAnimClass.forCurrent);
next.classList.add(moveSlideAnimClass.forNext);
dots[n].classList.add("active");
slideIndex=n;
captionText.style.display = "none";
captionText.className = "captionText "+slideTextAnimClass;
captionText.innerText=slides[n].querySelector(".captionText").innerText;
captionText.style.display = "block";
}
}
var timer=null;
function setTimer(){
timer=setInterval(function () {
plusSlides(1) ;
},6000);
}
setTimer();
function playPauseSlides() {
var playPauseBtn=document.getElementById("playPause");
if (timer==null){
setTimer();
playPauseBtn.style.backgroundPositionY = "0px"
}else{
clearInterval(timer);
timer=null;
playPauseBtn.style.backgroundPositionY = "-33px"
}
}.galleryContainer{
top: 0px;
position: relative;
width: 100%;
height: 580px;
max-width: 2000px;
margin: auto;
box-sizing: border-box;
background-color: red;
}
.galleryContainer .slideShowContainer{
width: 100%;
max-width: 1600px;
align-content: center;
height: 100%;
overflow: hidden;
background-color: gainsboro;
position: relative;
}
.galleryContainer .slideShowContainer #playPause{
width: 32px;
height: 32px;
position: absolute;
background-image: url(/img/playPause.png);
background-repeat: no-repeat;
z-index: 5;
background-size: cover;
margin: 5px;
cursor: pointer;
top: 90%;
}
.galleryContainer .slideShowContainer #playPause:hover{
opacity: .7;
}
.galleryContainer .slideShowContainer .imageHolder{
width: 100%;
height: 100%;
position: absolute;
opacity: 0;
}
.galleryContainer .slideShowContainer .imageHolder img{
width: 100%;
min-width: 1600px;
height: 100%;
background-size: cover;
}
.galleryContainer .slideShowContainer .imageHolder .captionText{
display: none;
}
.galleryContainer .slideShowContainer .imageHolder .btnSlider{
position: absolute;
display: block;
width: 220px;
height: 40px;
font-size: 20px;
text-decoration: none;
left: 50%;
top: 350px;
padding-top: 4px;
text-align: center;
border: 2px solid #FF0000;
border-radius: 15px;
transition: all 0.5s;
color: red;
}
.galleryContainer .slideShowContainer .leftArrow,.galleryContainer .slideShowContainer .rightArrow{
width: 50px;
background: #00000036;
position: absolute;
left: 0;
z-index: 3;
transition: background 0.5s;
height: 72px;
top: 50%;
transform: translateY(-50%);
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
}
.galleryContainer .slideShowContainer .rightArrow{
left: auto;
right: 0;
border-top-right-radius: 0px;
border-bottom-right-radius: 0px;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
}
.galleryContainer .slideShowContainer .leftArrow:hover,.galleryContainer .slideShowContainer .rightArrow:hover{
background: #000000a8;
cursor: pointer;
}
.galleryContainer .arrow{
display: inline-block;
border: 3px solid white;
width: 10px;
height: 10px;
border-left: none;
border-bottom: none;
margin: auto;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
.galleryContainer .arrow.arrowLeft{
transform: rotateZ(-135deg);
}
.galleryContainer .arrow.arrowRight{
transform: rotateZ(45deg);
}
.galleryContainer .slideShowContainer>.captionTextHolder{
position: absolute;
bottom: 30%;
z-index: 1;
color: red;
font-family: "Nunito";
font-size: 40px;
text-align: left;
width: 400px;
height: 200px;
line-height: 35px;
overflow: hidden;
margin-left: 50%;
margin-right: auto;
}
.galleryContainer .slideShowContainer>.captionTextHolder>.captionText{
margin: 0;
}
.galleryContainer #dotsContainer{
position: absolute;
width: 10%;
height: 3%;
text-align: center;
padding-top: 0px;
box-sizing: border-box;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
bottom: 5%;
}
.galleryContainer #dotsContainer .dots{
display: inline-block;
width: 15px;
height: 15px;
border-radius: 50%;
margin-left: 5px;
background-color: #bbb;
cursor: pointer;
transition:background-color 0.5s;
}
.galleryContainer #dotsContainer .dots:first-child{
margin-left: 0;
}
.galleryContainer #dotsContainer .dots:hover,.galleryContainer #dotsContainer .dots.active{
background-color: #717171;;
}
.galleryContainer .moveLeftCurrentSlide{
animation-name: moveLeftCurrent;
animation-duration: 0.5s;
animation-timing-function: linear;
animation-fill-mode:forwards;
}
.galleryContainer .moveLeftNextSlide{
animation-name: moveLeftNext;
animation-duration: 0.5s;
animation-timing-function: linear;
animation-fill-mode:forwards;
}
@keyframes moveLeftCurrent {
from {margin-left: 0;opacity: 1;}
to {margin-left: -100%;opacity: 1;}
}
@keyframes moveLeftNext {
from {margin-left: 100%;opacity: 1;}
to {margin-left: 0%;opacity: 1;}
}
.galleryContainer .moveRightCurrentSlide{
animation-name: moveRightCurrent;
animation-duration: 0.5s;
animation-timing-function: linear;
animation-fill-mode:forwards;
}
.galleryContainer .moveRightPrevSlide{
animation-name: moveRightPrev;
animation-duration: 0.5s;
animation-timing-function: linear;
animation-fill-mode:forwards;
}
@keyframes moveRightCurrent {
from {margin-left: 0;opacity: 1;}
to {margin-left: 100%;opacity: 1;}
}
@keyframes moveRightPrev {
from {margin-left: -100%;opacity: 1;}
to {margin-left: 0%;opacity: 1;}
}
.slideTextFromBottom {
animation-name: slideTextFromBottom;
animation-duration: 0.7s;
animation-timing-function: ease-out;
}
@keyframes slideTextFromBottom {
from {opacity: 0;margin-top: 100px}
to {opacity: 1;margin-top: 0px;}
}
.slideTextFromTop {
animation-name: slideTextFromTop;
animation-duration: 0.7s;
animation-timing-function: ease-out;
}
@keyframes slideTextFromTop {
from {opacity: 0;margin-top: -100px}
to {opacity: 1;margin-top: 0px;}
} <div class = "galleryContainer">
<div class = "slideShowContainer">
<div id = "playPause" onclick = "playPauseSlides()"></div>
<div onclick = "plusSlides(-1)" class = "nextPrevBtn leftArrow"><span class = "arrow arrowLeft"></span></div>
<div onclick = "plusSlides(1)" class = "nextPrevBtn rightArrow"><span class = "arrow arrowRight"></span></div>
<div class = "captionTextHolder"><p class = "captionText slideTextFromTop"></p></div>
<div class = "imageHolder">
<img src = "https://picsum.photos/g/1600/500/?random">
<a href = "#" class = "captionText">Todo lo que necesitas en un solo lugar</a>
<a href = "#" class = "btnSlider">Mas informacion</a>
</div>
<div class = "imageHolder">
<img src = "https://picsum.photos/g/1600/500/?random">
<p class = "captionText">Caption Text-02</p>
</div>
<div class = "imageHolder">
<img src = "https://picsum.photos/g/1600/500/?random">
<p class = "captionText">Caption Text-03</p>
</div>
<div class = "imageHolder">
<img src = "https://picsum.photos/g/1600/500/?random">
<p class = "captionText">Caption Text-04</p>
</div>
</div>
<div id = "dotsContainer"></div>
</div>пожалуйста, добавьте свой HTML / CSS
Здравствуйте, спасибо за ответы! здесь вы можете посмотреть код: codepen.io/carlos-ojeda/pen/KbXOKv
Карлос, не могли бы вы отредактировать и добавить сюда код? Если вы используете ссылки, они часто исчезают, а ответ в будущем станет бесполезным для других. Также неразумно просить людей уходить с места, чтобы помочь.
Хорошо, я добавил код на этот сайт, спасибо за хороший совет.
Вы хотите, чтобы кнопка mas informacion была на всех страницах? В этом случае вам нужно будет создать элемент btnSlider внутри всех элементов imageHolder.
Да, я знал это, спасибо. Я хочу, чтобы тег «a» работал как ссылка или кнопка, но в моем коде его даже нельзя выбрать.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Сделано и работает (Опять !!!). Я перемещаю ссылки в div и заменяю селектор .innerText на .innerHTML (но ссылки теперь выглядят как ссылки, поэтому вам нужно стилизовать их). Да, это может быть проще, но это тоже работает.
var slideIndex,slides,dots,captionText;
function initGallery(){
// 1 para ocultar y mostrar imageHolder con opasity 0
slideIndex = 0;
slides=document.getElementsByClassName("imageHolder"); // slides=4
slides[slideIndex].style.opacity=1;
// 2 para mostrar las letras
captionText=document.querySelector(".captionTextHolder .captionText");
captionText.innerHTML=slides[slideIndex].querySelector(".captionText").innerHTML;
// 3 disable nextPrevBtn if slide count is one
if (slides.length<2){
var nextPrevBtns=document.querySelector(".leftArrow,.rightArrow");
nextPrevBtns.style.display = "none";
for (i = 0; i < nextPrevBtn.length; i++) {
nextPrevBtn[i].style.display = "none";
}
}
// 4 add dots
dots=[];
var dotsContainer=document.getElementById("dotsContainer"),i;
for (i = 0; i < slides.length; i++) {
var dot=document.createElement("span");
dot.classList.add("dots");
dotsContainer.append(dot);
dot.setAttribute("onclick","moveSlide("+i+")");
dots.push(dot);
}
dots[slideIndex].classList.add("active");
}
// botones de izquierda y derecha
initGallery();
function plusSlides(n) {
moveSlide(slideIndex+n);
}
function moveSlide(n){
var i;
var current,next;
var moveSlideAnimClass = {
forCurrent:"",
forNext:""
};
var slideTextAnimClass;
if (n>slideIndex) {
if (n >= slides.length){n=0;}
moveSlideAnimClass.forCurrent = "moveLeftCurrentSlide";
moveSlideAnimClass.forNext = "moveLeftNextSlide";
slideTextAnimClass = "slideTextFromTop";
}else if (n<slideIndex){
if (n<0){n=slides.length-1;}
moveSlideAnimClass.forCurrent = "moveRightCurrentSlide";
moveSlideAnimClass.forNext = "moveRightPrevSlide";
slideTextAnimClass = "slideTextFromBottom";
}
if (n!=slideIndex){
next = slides[n];
current=slides[slideIndex];
for (i = 0; i < slides.length; i++) {
slides[i].className = "imageHolder";
slides[i].style.opacity=0;
dots[i].classList.remove("active");
}
current.classList.add(moveSlideAnimClass.forCurrent);
next.classList.add(moveSlideAnimClass.forNext);
dots[n].classList.add("active");
slideIndex=n;
captionText.style.display = "none";
captionText.className = "captionText "+slideTextAnimClass;
captionText.innerHTML=slides[n].querySelector(".captionText").innerHTML;
captionText.style.display = "block";
}
document.getElementsByClassName("captionTextHolder")[0].style.animation = "slideTextFromTop 1s";
setTimeout(function () { document.getElementsByClassName("captionTextHolder")[0].style.animation = "";} ,1000);
setTimeout(function() {document.getElementsByClassName('moveLeftCurrentSlide')[0].style.zIndex = 0;}, 500);
}
var timer=null;
function setTimer(){
timer=setInterval(function () {
plusSlides(1) ;
},6000);
}
setTimer();
function playPauseSlides() {
var playPauseBtn=document.getElementById("playPause");
if (timer==null){
setTimer();
playPauseBtn.style.backgroundPositionY = "0px"
}else{
clearInterval(timer);
timer=null;
playPauseBtn.style.backgroundPositionY = "-33px"
}
}.galleryContainer{
top: 0px;
position: relative;
width: 100%;
height: 580px;
max-width: 2000px;
margin: auto;
box-sizing: border-box;
background-color: red;
}
.galleryContainer .slideShowContainer{
width: 100%;
max-width: 1600px;
align-content: center;
height: 100%;
overflow: hidden;
background-color: gainsboro;
position: relative;
}
.galleryContainer .slideShowContainer #playPause{
width: 32px;
height: 32px;
position: absolute;
background-image: url(/img/playPause.png);
background-repeat: no-repeat;
z-index: 5;
background-size: cover;
margin: 5px;
cursor: pointer;
top: 90%;
}
.galleryContainer .slideShowContainer #playPause:hover{
opacity: .7;
}
.galleryContainer .slideShowContainer .imageHolder{
width: 100%;
height: 100%;
position: absolute;
opacity: 0;
}
.galleryContainer .slideShowContainer .imageHolder img{
width: 100%;
min-width: 1600px;
height: 100%;
background-size: cover;
}
.galleryContainer .slideShowContainer .imageHolder .captionText{
display: none;
}
.galleryContainer .slideShowContainer .imageHolder .btnSlider{
position: absolute;
display: block;
width: 220px;
height: 40px;
font-size: 20px;
text-decoration: none;
left: 50%;
top: 350px;
padding-top: 4px;
text-align: center;
border: 2px solid #fff;
border-radius: 15px;
transition: all 0.5s;
color: white;
}
.galleryContainer .slideShowContainer .leftArrow,.galleryContainer .slideShowContainer .rightArrow{
width: 50px;
background: #00000036;
position: absolute;
left: 0;
z-index: 3;
transition: background 0.5s;
height: 72px;
top: 50%;
transform: translateY(-50%);
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
}
.galleryContainer .slideShowContainer .rightArrow{
left: auto;
right: 0;
border-top-right-radius: 0px;
border-bottom-right-radius: 0px;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
}
.galleryContainer .slideShowContainer .leftArrow:hover,.galleryContainer .slideShowContainer .rightArrow:hover{
background: #000000a8;
cursor: pointer;
}
.galleryContainer .arrow{
display: inline-block;
border: 3px solid white;
width: 10px;
height: 10px;
border-left: none;
border-bottom: none;
margin: auto;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
.galleryContainer .arrow.arrowLeft{
transform: rotateZ(-135deg);
}
.galleryContainer .arrow.arrowRight{
transform: rotateZ(45deg);
}
.galleryContainer .slideShowContainer>.captionTextHolder{
position: absolute;
bottom: 30%;
z-index: 1;
color: white;
font-family: "Nunito";
font-size: 40px;
text-align: left;
width: 400px;
height: 200px;
line-height: 35px;
overflow: hidden;
margin-left: 50%;
margin-right: auto;
}
.galleryContainer .slideShowContainer>.captionTextHolder>.captionText{
margin: 0;
}
.galleryContainer #dotsContainer{
position: absolute;
width: 10%;
height: 3%;
text-align: center;
padding-top: 0px;
box-sizing: border-box;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;
bottom: 5%;
}
.galleryContainer #dotsContainer .dots{
display: inline-block;
width: 15px;
height: 15px;
border-radius: 50%;
margin-left: 5px;
background-color: #bbb;
cursor: pointer;
transition:background-color 0.5s;
}
.galleryContainer #dotsContainer .dots:first-child{
margin-left: 0;
}
.galleryContainer #dotsContainer .dots:hover,.galleryContainer #dotsContainer .dots.active{
background-color: #717171;;
}
.galleryContainer .moveLeftCurrentSlide{
animation-name: moveLeftCurrent;
animation-duration: 0.5s;
animation-timing-function: linear;
animation-fill-mode:forwards;
}
.galleryContainer .moveLeftNextSlide{
animation-name: moveLeftNext;
animation-duration: 0.5s;
animation-timing-function: linear;
animation-fill-mode:forwards;
}
@keyframes moveLeftCurrent {
from {margin-left: 0;opacity: 1;}
to {margin-left: -100%;opacity: 1;}
}
@keyframes moveLeftNext {
from {margin-left: 100%;opacity: 1;}
to {margin-left: 0%;opacity: 1;}
}
.galleryContainer .moveRightCurrentSlide{
animation-name: moveRightCurrent;
animation-duration: 0.5s;
animation-timing-function: linear;
animation-fill-mode:forwards;
}
.galleryContainer .moveRightPrevSlide{
animation-name: moveRightPrev;
animation-duration: 0.5s;
animation-timing-function: linear;
animation-fill-mode:forwards;
}
@keyframes moveRightCurrent {
from {margin-left: 0;opacity: 1;}
to {margin-left: 100%;opacity: 1;}
}
@keyframes moveRightPrev {
from {margin-left: -100%;opacity: 1;}
to {margin-left: 0%;opacity: 1;}
}
.slideTextFromBottom {
animation-name: slideTextFromBottom;
animation-duration: 0.7s;
animation-timing-function: ease-out;
}
@keyframes slideTextFromBottom {
from {opacity: 0;margin-top: 100px}
to {opacity: 1;margin-top: 0px;}
}
.slideTextFromTop {
animation-name: slideTextFromTop;
animation-duration: 0.7s;
animation-timing-function: ease-out;
}
@keyframes slideTextFromTop {
from {padding-bottom: 90%;}
to {padding-bottom: 0;}
} <div class = "galleryContainer">
<div class = "slideShowContainer">
<div id = "playPause" onclick = "playPauseSlides()"></div>
<div onclick = "plusSlides(-1)" class = "nextPrevBtn leftArrow"><span class = "arrow arrowLeft"></span></div>
<div onclick = "plusSlides(1)" class = "nextPrevBtn rightArrow"><span class = "arrow arrowRight"></span></div>
<div class = "captionTextHolder"><p class = "captionText slideTextFromTop"></p></div>
<div class = "imageHolder">
<img src = "https://picsum.photos/g/1600/500/?random">
<div class = "captionText"><a href = "#">Todo lo que necesitas en un solo lugar</a><br><br>
<a href = "#">Mas informacion</a>
</div></div>
<div class = "imageHolder">
<img src = "https://picsum.photos/g/1600/500/?random">
<p class = "captionText">Caption Text-02</p>
</div>
<div class = "imageHolder">
<img src = "https://picsum.photos/g/1600/500/?random">
<p class = "captionText">Caption Text-03</p>
</div>
<div class = "imageHolder">
<img src = "https://picsum.photos/g/1600/500/?random">
<p class = "captionText">Caption Text-04</p>
</div>
</div>
<div id = "dotsContainer"></div>
</div>Большое тебе спасибо! Последний вопрос: как вы думаете, возможно ли иметь текст и анимацию кнопок, которая перемещается сверху вниз, как в первом примере?
Возможно почти все, так что да, но работы будет много :-)
Намек? Я думаю, что мой код избыточен и обширен, я думаю, что это могло бы быть проще.
@CarlosOjeda Я думал, что будет сложнее. Да, конечно, можно и попроще.
Хороший! Хотел бы я когда-нибудь программировать, как ты. Теперь почти все работает идеально, тем не менее, когда вы видите последний слайд и когда он возвращается к первому слайду, слева появляется небольшая линия, что-то вроде изображения не заполняет весь слайд. Я думаю, это может быть ошибка в коде JavaScript, как вы думаете?
У вас может быть проблема с z-индексом, но информации о ней недостаточно, чтобы знать наверняка.