Sass 带字符串的算术运算

Sass 带字符串的算术运算,sass,Sass,上面的代码是不言自明的。请更正。您可以使用calc功能 .selector { $width: '10px'; width: (#{$width}/2); // output: "10px", but expected: 5px } 更新: 基于“”文章的解决方案 萨斯梅斯特 到数字功能 输入:“10px”,输出:10 输入:10px,输出:10px .selector { $width: '10px'; width: calc(#{$width}/2); } 至

上面的代码是不言自明的。请更正。

您可以使用
calc
功能

.selector {
    $width: '10px';
    width: (#{$width}/2); // output: "10px", but expected: 5px
}

更新:

基于“”文章的解决方案

萨斯梅斯特

到数字功能
输入:“10px”,输出:10
输入:10px,输出:10px

.selector  {
  $width: '10px';
  width: calc(#{$width}/2);
}
至装置功能
输入:“20px”,输出:1px
输入:35%,输出:1%

@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);;
}
函数使用。首先从字符串中获取数字。其次,从字符串中获取单位。然后将数字乘以单位:

@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;
}
生成的css:

.selector {
  $size: '10px';

  $number: to-number($size);
  $unit: to-unit($size);
  width: ($number * $unit) / 2;
}

不要使用字符串定义
$width
的值,然后在
#{}
括号内进行计算:

.selector {
  width: 5px;
}
输出:

.selector {
    $width: 10px;
    width: #{$width / 2};
}

calc()
只有在对动态值执行计算时才有必要,但当所有输入静态已知时,则使用预处理器进行处理。

它可以工作,但calc不向后兼容。sass中没有任何其他解决方案或任何类型转换功能。sass中没有内置的将字符串转换为数字的功能。你可以手工做。我将尝试编写代码。谢谢!还请建议任何库或第三方代码片段来实现same@Rajkishore如果这个答案对你有帮助,你能把它标记为有用吗:-)谢谢你的努力,它对我有用。但与其他脚本语言相比,它的许多行代码只是为了实现非常简单的事情。是不是应该有一些本地的方法来做呢。好奇!。
.selector {
  width: 5px;
}