2

使用 SASS/SCSS。我有以下内容:

body:not(.sessions):not(.registrations):not(.home):not(.posts.new) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

这根本不可读。如何通过使用类数组来重构它:

$full-page-classes: .sessions .registrations .home .posts.new
4

1 回答 1

1

如果我理解你的意思是正确的,你可能想像这样使用数组

$full-page-classes: '.sessions', '.registrations', '.home', '.posts.new';

@each $page-class in $full-page-classes {
  body:not(#{$page-class}) {
    padding-top: 4.5rem;
    padding-bottom: 7rem;
  }
}

输出:

body:not(.sessions) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

body:not(.registrations) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

body:not(.home) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

body:not(.posts.new) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

你可以在sassmeister上试试


更新:

如果你想生成内联CSS,你可以试试这个:

$full-page-classes: '.sessions', '.registrations', '.home', '.posts.new';

$temp: '';

@each $page-class in $full-page-classes {
  $temp: $temp + ':not(#{$page-class})';
}

@each $item in $temp {
  body#{$item} {
    padding-top: 4.5rem;
    padding-bottom: 7rem;
  }
}

输出:

body:not(.sessions):not(.registrations):not(.home):not(.posts.new) {
  padding-top: 4.5rem;
  padding-bottom: 7rem;
}

更新 2:

@function str-replace($string, $search, $replace: '') {
  $index: str-index($string, $search);

  @if $index {
    @return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
  }

  @return $string;
}

$full-page-classes: ' .sessions, .registrations, .home, .posts.new,';

@each $x in str-replace(str-replace($full-page-classes, ' ', ':not('), ',', ')') {
  body#{$x} {
    padding-top: 4.5rem;
    padding-bottom: 7rem;
  }
}

参考:str-replace 函数

于 2019-12-31T06:38:03.813 回答