提问者:小点点

范围滑块根据值更改拇指背景图像


我有一个范围滑块,它的值从1到5。 对于每个值,我希望滑块拇指更改为不同的图像。

CSS:

.slider {
    -webkit-appearance: none;
    width: 100%;
    height: 5px;
    border-radius: 5px;
    background: #FFFFFF;
    outline: none;
    opacity: 0.7;
    -webkit-transition: .2s;
    transition: opacity .2s;
}
.slider:hover {
    opacity: 1;
}
.slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 100px;
    height: 100px;
    border: 0;
    border-radius: 50%;
    background-image: url("{% static 'img/coffee_cup.png' %}");
    background-size: contain;
    background-position: center center;
    background-repeat: no-repeat;
    cursor: pointer;
}
.slider::-moz-range-thumb {
    width: 100px;
    height: 100px;
    border: 0;
    border-radius: 50%;
    background-image: url("{% static 'img/coffee_cup.png' %}");
    background-size: contain;
    background-position: center center;
    background-repeat: no-repeat;
    cursor: pointer;
}

HTML

<input type="range" min="1" max="5" value="1" class="slider" id="roast-level">

基本上现在拇指背景图像被设置为静态图像。 如果范围的值是2,我想改变它,如果是5,我想改变为“coffee_cup2.png”,基本上我有5个不同的图像为这个准备好了“coffee_cup5.png”。

我相信javascript是所需要的,但我不确定如何去做。

感谢任何帮助。


共1个答案

匿名用户

null

var slide = document.getElementById('roast-level');
slide.onchange = function() {
  var imgArr = [{
    Val: 1,
    Url: 'https://faviana.com/blog/wp-content/uploads/2017/04/cup-of-coffee-200x200.jpg'
  }, {
    Val: 2,
    Url: 'https://onlinejpgtools.com/images/examples-onlinejpgtools/coffee-resized.jpg'
  }, {
    Val: 3,
    Url: 'https://anti-aging.myblog.it/wp-content/uploads/sites/224035/2015/08/150824_coffee_beans.jpg'
  }, {
    Val: 4,
    Url: 'https://www.businessplantemplate.com/wp-content/uploads/2016/04/coffee-shop-200x200.jpg'
  }, {
    Val: 5,
    Url: 'https://fitsmallbusiness.com/wp-content/uploads/2017/04/CoffeePR-200x200.jpg'
  }];
  document.body.style.setProperty("--dynamicImage", "url('" + imgArr.filter(a => a.Val == this.value)[0].Url + "')");
}
body {
  background-color: black;
  --dynamicImage: url("https://faviana.com/blog/wp-content/uploads/2017/04/cup-of-coffee-200x200.jpg");
}
.slider {
    -webkit-appearance: none;
    width: 100%;
    height: 5px;
    border-radius: 5px;
    background: #FFFFFF;
    outline: none;
    opacity: 0.7;
    -webkit-transition: .2s;
    transition: opacity .2s;
}
.slider:hover {
    opacity: 1;
}
.slider::-webkit-slider-thumb {
    -webkit-appearance: none;
    appearance: none;
    width: 100px;
    height: 100px;
    border: 0;
    border-radius: 50%;
    background-image: var(--dynamicImage);
    background-size: contain;
    background-position: center center;
    background-repeat: no-repeat;
    cursor: pointer;
}
<input type="range" min="1" max="5" value="1" class="slider" id="roast-level">