How to rotate input type range thumb in javascript

2019-04-02 05:38发布

I have an <input type="range"> and want to rotate the thumb - but only the thumb on input.

My problem is: When i try to rotate it, it rotates the whole slider.

Can someone help me?

function slide(event){
  event.target.style.webkitTransform = 'rotate(20deg)';
}
        .slidecontainer {
            width: 100%;
        }
        .slider {
            -webkit-appearance: none;
            appearance: none;
            width: 100%;
            height: 20px;
            background: #d3d3d3;
            outline: none;
            opacity: 0.7;
            -webkit-transition: .2s;
            transition: opacity .2s;
            border-radius: 20px;
        }
        .slider:hover {
            opacity: 1;
        }
        .slider::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 50px;
            height: 50px;
            border-radius: 50px;
            background: grey;
            background-image: url(img/thumb.png);
            background-size: 35px 35px;
            background-position: center;
            background-repeat: no-repeat;
            cursor: pointer;
        }
        .slider::-moz-range-thumb {
            width: 50px;
            height: 50px;
            border-radius: 50px;
            background: grey;
            background-image: url(img/thumb.png);
            background-size: 35px 35px;
            background-position: center;
            background-repeat: no-repeat;
            cursor: pointer;
        }
<div class="slidecontainer">
  <input type="range" min="100" max="500" value="300" class="slider" oninput="slide(event)">
</div>

1条回答
闹够了就滚
2楼-- · 2019-04-02 05:52

Since you cannot target pseudo-element using JS, consider using CSS variable. You define them within the input element and they are inherited by the thumb; thus you can easily achieve what you want.

function slide(event) {
  event.target.style.setProperty('--r',event.target.value+'deg');
}
.slidecontainer {
  width: 100%;
}

.slider {
  -webkit-appearance: none;
  appearance: none;
  width: 100%;
  height: 20px;
  background: #d3d3d3;
  outline: none;
  opacity: 0.7;
  transition: opacity .2s;
  border-radius: 20px;
}

.slider:hover {
  opacity: 1;
}

.slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background:linear-gradient(red 50%,blue 0);
  cursor: pointer;
  display:inline-block;
  transform:rotate(var(--r,180deg));
}

.slider::-moz-range-thumb {
  width: 50px;
  height: 50px;
  border-radius: 50px;
  background: linear-gradient(red 50%,blue 0);
  cursor: pointer;
  display:inline-block;
  transform:rotate(var(--r,180deg));
}
<div class="slidecontainer">
  <input type="range" min="0" max="360" value="180" class="slider" oninput="slide(event)">
</div>

查看更多
登录 后发表回答