1
.selector {
$width: '10px';
width: (#{$width}/2); // output: "10px", but expected: 5px
}
위 코드는 자체 설명입니다. 제발 고쳐주세요.문자열을 사용한 SCSS 산술
.selector {
$width: '10px';
width: (#{$width}/2); // output: "10px", but expected: 5px
}
위 코드는 자체 설명입니다. 제발 고쳐주세요.문자열을 사용한 SCSS 산술
calc
기능을 사용할 수 있습니다.
.selector {
$width: '10px';
width: calc(#{$width}/2);
}
업데이트 : "Casting a string to a number in Sass"기사에 기반
솔루션.
새 스미 스터 demo.
~ 기능
입력 : '10px', 출력 : 10;
입력 : 10px 출력 : 10px
@function to-number($value) {
@if type-of($value) == 'number' {
@return $value;
} @else if type-of($value) != 'string' {
@error 'Value for `to-number` should be a number or a string.';
}
$result: 0;
$digits: 0;
$minus: str-slice($value, 1, 1) == '-';
$numbers: ('0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9);
@for $i from if($minus, 2, 1) through str-length($value) {
$character: str-slice($value, $i, $i);
@if (index(map-keys($numbers), $character) or $character == '.') {
@if $character == '.' {
$digits: 1;
} @else if $digits == 0 {
$result: $result * 10 + map-get($numbers, $character);
} @else {
$digits: $digits * 10;
$result: $result + map-get($numbers, $character)/$digits;
}
}
}
@return if($minus, -$result, $result);;
}
행 단위 함수
입력 '20 픽셀'출력 : 1 픽셀;
입력 : '35 % ', 출력 : 1 %
@function to-unit($value) {
@if type-of($value) != 'string' {
@error 'Value for `to-unit` should be a string.';
}
$units: ('px': 1px, 'cm': 1cm, 'mm': 1mm, '%': 1%, 'ch': 1ch, 'pc': 1pc, 'in': 1in, 'em': 1em, 'rem': 1rem, 'pt': 1pt, 'ex': 1ex, 'vw': 1vw, 'vh': 1vh, 'vmin': 1vmin, 'vmax': 1vmax);
$parsed-unit: false;
@each $unit in $units {
// str-index - find substring in a string
// 'px' in '10px' for example
// $unit is a pair of ['px': 1px] (item in $units)
// nth(['px': 1px], 1) returns 'px'
// nth(['px': 1px], 2) returns 1px
@if (str-index($value, nth($unit, 1))) {
$parsed-unit: nth($unit, 2);
}
}
@if (not $parsed-unit) {
@error 'Invalid unit `#{$value}`.';
}
@return $parsed-unit;
}
기능의 사용. 먼저 문자열에서 숫자를 가져옵니다. 둘째, 문자열에서 유닛을 가져옵니다. 그런 다음 단위로 수를 곱
.selector {
$size: '10px';
$number: to-number($size);
$unit: to-unit($size);
width: ($number * $unit)/2;
}
생성 된 CSS :
.selector {
width: 5px;
}
잘 작동하지만 CALC는 호환되지 않습니다. 이것에 대한 다른 해결책이나 sass의 typecasting 기능이 없습니까? – Rajkishore
문자열을 숫자로 변환하는 기능이 내장되어 있지 않습니다. 수동으로 할 수 있습니다. 코드를 작성하려고합니다. – 3rdthemagical
감사합니다. – Rajkishore