clamp
将一个数字限制在给定的最小值和最大值之间。如果你提供的数字小于最小值,则返回最小值;如果大于最大值,则返回最大值;如果介于最小值和最大值之间,则原样返回该数字。
加载中...
从以下方法签名中选择一个——要么立即获取一个被限制后的值,要么省略valueToClamp
参数以获取一个可重复使用的函数该函数会记住最小值和最大值,这样你之后可以多次传入需要限制的值:
1) clamp(最小值, 最大值, 要限制的值)
- 最小值: 数字 - 最小值
- 最大值: 数字 - 最大值
- 要限制的值: 数字 - 应该被限制在前两个值之间的数值。
返回: 被限制后的数字
示例
// set the clamping range to between 0 and 100, and clamp 105
gsap.utils.clamp(0, 100, 105); // returns 100
// in the same range, clamp -50
gsap.utils.clamp(0, 100, -50); // returns 0
// and clamp 20
gsap.utils.clamp(0, 100, 20); // returns 20
2) clamp(最小值, 最大值)
- 最小值: 数字 - 最小值
- 最大值: 数字 - 最大值
返回: 一个可重复使用的函数,接受一个参数——要限制的值
如果你省略了valueToClamp
(第三个)参数,该工具方法将返回一个可重复使用的函数该函数已准备好根据最初提供的最小值和最大值来限制任何值。换句话说,返回的函数会记住最小值和最大值,因此之后你可以非常快速高效地多次进行限制。
示例
// get a clamping function that will always clamp to a range between 0 and 100
var clamper = gsap.utils.clamp(0, 100); // notice we didn't provide a valueToClamp
// now we can reuse the function to clamp any values:
console.log(clamper(105)); // 100
console.log(clamper(-50)); // 0
console.log(clamper(20)); // 20
提示:组合使用多个可重复使用的函数实现强大的数据转换!
你可以pipe()
将几个可重复使用的函数限制范围, 映射到另一个范围,对齐, 插值,以及等等。例如:
// get a clamping function that will always clamp to a range between 0 and 100
var transformer = gsap.utils.pipe(
// clamp between 0 and 100
gsap.utils.clamp(0, 100),
// then map to the corresponding position on the width of the screen
gsap.utils.mapRange(0, 100, 0, window.innerWidth),
// then snap to the closest increment of 20
gsap.utils.snap(20)
);
// now we feed one value in and it gets run through ALL those transformations!:
transformer(25.874);