index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="style.css" />
    <title>Document</title>
  </head>
  <body>
    <main>
      <div class="slider">
        <!-- 显示选择的数值容器 -->
        <span class="selected">
          50
        </span>
        <!-- 滑动选择器 -->
        <input type="range" id="slider-input" min="0" max="500" value="50" />
      </div>
    </main>
    <script src="index.js"></script>
  </body>
</html>

css

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: Helvetica, "PingFang SC", "Microsoft Yahei", sans-serif;
}

main {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-color: #1e272e;
}

/* 选择器容器 */
.slider {
  width: 50%;
  display: flex;
  align-items: center;
}

input[type="range"] {
  /* 禁用浏览器默认外观 */
  -webkit-appearance: none;
  background: linear-gradient(75deg, #3c40c6 0%, #575fcf 100%);
  border-radius: 4px;
  width: 100%;
  height: 12px;
  outline: none;
  box-shadow: 0 0 6px rgb(28, 32, 148);
}

/* 滑动选择器上的滑动按钮 */
input[type="range"]::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  background-color: #f53b57;
  transition: 0.3s;
}

/* 当滑动选择器上的滑动按钮滑动时 */
input[type="range"]:active::-webkit-slider-thumb {
  background-color: #ef5777;
  box-shadow: 0 0 0 6px rgba(155, 73, 146, 0.4);
}

/* 显示数值的容器 */
.selected {
  margin-right: 16px;
  background-color: #f53b57;
  width: 80px;
  line-height: 40px;
  text-align: center;
  color: white;
  border-radius: 4px;
  position: relative;
}

/* 三角 */
.selected::after {
  content: "";
  display: block;
  border-top: 8px solid transparent;
  border-left: 8px solid #f53b57;
  border-bottom: 8px solid transparent;
  position: absolute;
  top: calc(50% - 8px);
  right: -6px;
}

js部分

// 获取滑动选择器实例
const sliderEl = document.querySelector("#slider-input");
// 获取数值显示容器实例
const selectedEl = document.querySelector(".selected");

// 监听滑动事件
sliderEl.addEventListener("input", () => {
  selectedEl.innerHTML = sliderEl.value;
});

版权声明:本文为前端导师歌谣的博客原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/yao-655442/p/16933107.html