unitize
返回值:函数
可以将其想象成对unitize()
函数的封装,其他确保结果会附加一个单位,比如"px"
或者"%"
。例如,您可能有一个只处理原始数字的函数,如wrap(),但需要在结果末尾添加一个"px"
单位。或者传入的值已经带有单位,因此您需要先去掉这些单位,再将其输入到您的函数中(本例中为wrap()),然后再将相同的单位应用回结果末尾。没问题!
示例
// get a function that always applies "px" to the result (and strips off any units from the input)
var clamp = gsap.utils.unitize(gsap.utils.clamp(0, 100), "px");
// now the result always gets "px" added:
clamp(132); // "100px"
clamp("-20%"); // "0px" (notice the unit change)
clamp(50); // "50px"
// or use whatever unit is in the input:
var wrap = gsap.utils.unitize(gsap.utils.wrap(0, 100)); // no specific unit is declared in unitize()
wrap("150px"); // 50px
wrap("130%"); // 30%
// another example of forcing a unit like "%":
var map = gsap.utils.unitize(gsap.utils.mapRange(-10, 10, 0, 100), "%");
map(0); // 50%
map("5px"); // 75%
// useful in modifier functions:
gsap.to(".class", {
x: 1000,
modifiers: {
//the value fed into this function will have unit - this strips it off to feed in a raw number to wrap() and then slaps "px" onto the result.
x: gsap.utils.unitize(gsap.utils.wrap(0, window.innerWidth), "px"),
},
});
参数
- 函数func:Function(函数) - 其结果应该被附加单位的函数。
- unit(单位):String(字符串)*(可选)* - 始终附加到结果末尾的单位。如果省略此参数,则会动态地应用输入值中的原始单位。
注意:unitize()
在将其传递给目标函数之前,使用parseFloat()
方法从输入中移除任何单位(单位化)。function
.