let slideIndex = 1;
showSlides(slideIndex)
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
const slajdovi = document.getElementsByClassName('slajd')
const točke = document.getElementsByClassName('točka');
if (n > slajdovi.length) {slideIndex = 1}
if (n < 1) {slideIndex = slajdovi.length}
for (let i = 0; i < slajdovi.length; i++) {
slajdovi[i].style.display = 'none';
}
for (let i = 0; i < točke.length; i++) {
točke[i].style.backgroundColor = '';
}
slajdovi[slideIndex-1].style.display = "flex";
točke[slideIndex-1].style.backgroundColor = "var(--zlatni-tekst-boja)";
}
我尝试将其绑定到 plusSlides() 函数,但没有任何效果,还尝试将其替换为“slajdovi[i].style.display = 'none';”行无济于事。有人可以帮助我吗?该代码是从 w3 复制的,目前按预期工作,但我希望它在单击按钮时滑动,而不是只是消失和出现。
1.Ensure your HTML structure supports horizontal scrolling:-
<div id="slajdoviContainer" style="overflow-x: hidden; white-space: nowrap; width: 100%; position: relative;">
<div class="slajd" style="display: inline-block; width: 100%;">Slide 1</div>
<div class="slajd" style="display: inline-block; width: 100%;">Slide 2</div>
<div class="slajd" style="display: inline-block; width: 100%;">Slide 3</div>
<!-- Add more slides as needed -->
</div>
<div class="točke-container">
<span class="točka" onclick="currentSlide(1)"></span>
<span class="točka" onclick="currentSlide(2)"></span>
<span class="točka" onclick="currentSlide(3)"></span>
<!-- Add more točke as needed -->
</div>
<button onclick="plusSlides(-1)">Previous</button>
<button onclick="plusSlides(1)">Next</button>
2.Add CSS for smooth scrolling:-
#slajdoviContainer {
scroll-behavior: smooth;
}
3.Update your JavaScript to handle horizontal scrolling:-
let slideIndex = 1;
showSlides(slideIndex);
function plusSlides(n) {
showSlides(slideIndex += n);
}
function currentSlide(n) {
showSlides(slideIndex = n);
}
function showSlides(n) {
const slajdovi = document.getElementsByClassName('slajd');
const točke = document.getElementsByClassName('točka');
const slajdoviContainer = document.getElementById('slajdoviContainer');
const slideWidth = slajdovi[0].offsetWidth; // Assuming all slides have the same width
if (n > slajdovi.length) { slideIndex = 1; }
if (n < 1) { slideIndex = slajdovi.length; }
// Scroll to the appropriate slide
slajdoviContainer.scrollLeft = slideWidth * (slideIndex - 1);
// Update the dots
for (let i = 0; i < točke.length; i++) {
točke[i].style.backgroundColor = '';
}
točke[slideIndex - 1].style.backgroundColor = "var(--zlatni-tekst-boja)";
}
- Now, when you click the "Previous" or "Next" buttons, the slides will smoothly scroll horizontally instead of just appearing and disappearing.