gpt4 book ai didi

javascript - slider 背景

转载 作者:行者123 更新时间:2023-11-30 06:09:54 26 4
gpt4 key购买 nike

我有一个 slider ,需要在不使用 .style.backgroundImage 的情况下更改背景。那么我该如何通过向 slider 或其他东西添加一些类来做到这一点呢?

'use strict'

let backgroundSlides = ['url(\'/images/slider/burger-background.jpg\')',
'url(\'/images/slider/pizza-background.jpg\')',
'url(\'/images/slider/soup-background.jpg\')',
'url(\'/images/slider/sushi-background.jpg\')'
];

let sliderElement = document.querySelector('.slider');
let sliderBtn = document.querySelectorAll('.slider-button');

for (let i = 0; i < sliderBtn.length; i++) {
sliderBtn[i].addEventListener('click', function() {
sliderElement.style.backgroundImage = backgroundSlides[i];
});
}
<div class="slider">
<div class="slider-btns">
<input type="radio" name="slider button" id="slider-btn-1">
<label class="slider-button" for="slider-btn-1"></label>
<input type="radio" name="slider button" id="slider-btn-2">
<label class="slider-button" for="slider-btn-2"></label>
<input type="radio" name="slider button" id="slider-btn-3">
<label class="slider-button" for="slider-btn-3"></label>
<input type="radio" name="slider button" id="slider-btn-4">
<label class="slider-button" for="slider-btn-4"></label>
</div>
</div>

最佳答案

有类:为每个输入创建一个类并在其中设置背景图像。

<style>
.slider-btn-1 {background-image: url('/images/slider/burger-background.jpg');}
.slider-btn-2 {background-image: url('/images/slider/pizza-background.jpg');}
.slider-btn-3 {background-image: url('/images/slider/soup-background.jpg');}
.slider-btn-4 {background-image: url('/images/slider/sushi-background.jpg');}
</style>

现在您只需更改类属性即可。

<script>
let sliderElement = document.querySelector('.slider');
let sliderBtn = document.querySelectorAll('.slider-button');

for(let i = 0; i < sliderBtn.length; i++){
sliderBtn[i].addEventListener('click', function(){
sliderElement.className = 'slider ' + sliderBtn[i].htmlFor;//Or another attribute where the className is in
});
}
</script>

关于javascript - slider 背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59522274/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com