我正在构建一个价格范围滑块,其中包含2个输入(从最低价格到最高价格)以及一条SVG线,该线会在滑块的滑块内左右移动。
我正在努力寻找该功能的数学方程式,因为如果可行的话,左SVG x1值需要为0而不是最小输入值。
我留下了一个codeSandBox,以便大家看看我在尝试实现的目标。
https://codesandbox.io/s/practical-bush-qq7dl?file=/src/App.js
import React, { useState } from "react";
export default function App() {
const [minRange, setMinRange] = useState("");
const [maxRange, setMaxRange] = useState("");
const [staticRange, setStaticRange] = useState({
min: 20,
max: 112
});
const rangeSplit = staticRange.min + staticRange.max / 2;
const handleChange = (input, e) => {
const value = e.target.value;
input === "min" ? setMinRange(value) : setMaxRange(value);
};
return (
<div className="slider">
<div className="slider__inputs">
<input
min={staticRange.min}
max={rangeSplit}
type="range"
value={minRange}
onChange={(e) => handleChange("min", e)}
/>
<input
min={rangeSplit}
max={staticRange.max}
type="range"
value={maxRange}
onChange={(e) => handleChange("max", e)}
/>
<svg width="100%" height="4">
<line
x1={minRange}
y1="0"
x2={maxRange}
y2="0"
stroke="#444"
stroke-width="12"
></line>
</svg>
</div>
<div className="slider__range">
<span>{`£${minRange}`}</span>
<span>{`£${maxRange}`}</span>
</div>
</div>
);
}
所需效果:
您的svg线是以%定义的,因此您需要将x1,x2值转换为百分比,如上所示的kca。
因此,您要做的就是将总范围计算为staticRange.max-staticRange.min。
const totalRange=(staticRange.max - staticRange.min);
此外,您需要将范围拆分设置为静态最小值和最大值之间的位置,因此,如果最小值为20,最大值为112,则rangeSplit必须为66,(66比20大46,并且46小于112)。
const rangeSplit = staticRange.min+(totalRange / 2);
然后,在定义x1和x2点时,将滑块位置与staticRange.min值之间的差值求和,将其隐含为%。
x1={(100 * ((minRange-staticRange.min)/totalRange)) + "%"}
x2={(100 * ((maxRange-staticRange.min)/totalRange)) + "%"}
因此,您可以看到,当minRange == staticRange.min时,该值为0%;当maxRange == staticRange.max时,该值是totalRange / totalRange,等于100%。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句