使用 String.prototype.match() 获取包含数值的 3 个字符串的数组。
使用 Array.prototype.map() 结合 Number 将它们转换为数值数组。
使用 Math.max() 和 Math.min() 确保亮度在有效范围内(介于0和之间100)。
使用模板文字创建 hsl() 具有更新值的新字符串。
JavaScript
const changeLightness = (delta, hslStr) => {
const [hue, saturation, lightness] = hslStr.match(/\d+/g).map(Number);
const newLightness = Math.max(
0,
Math.min(100, lightness + parseFloat(delta))
);
return `hsl(${hue}, ${saturation}%, ${newLightness}%)`;
};
示例:
changeLightness(10,'hsl(330, 50%, 50%)');// 'hsl(330, 50%, 60%)'
changeLightness(-10,'hsl(330, 50%, 50%)');// 'hsl(330, 50%, 40%)'
更多内容请访问我的网站:https://www.icoderoad.com