如何使用sass / compass缩短这个占位符转换的CSS选择器?

时间:2013-05-25 09:21:02

标签: css css-selectors sass compass-sass

因此,我决定使用SASS使用CSS过渡制作一个非常动画的搜索框(demo)。我还想为占位符文本设置动画,其中涉及four different pesudo-classes,源代码现在看起来像这样:

input {
  background-image:url(search.png);
  background-repeat:no-repeat;
  background-size:20px 20px;
  background-position-x:12px;
  background-position-y:10px;
  background-color:#6E597E;
  box-shadow:0 0 5px #333 inset;
  border-radius:15px;
  border:0;
  padding:8px 10px 10px 45px;
  font-size:20px;
  font-weight:300;
  font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
  color:#BBB;
  width:100%;
  transition:all 0.5s ease;
  &:focus {
    outline:none;
    box-shadow:0 0 10px #333 inset;
    background-color:#85699A;
    color:#EEE;

    &::-webkit-input-placeholder { color:#DDD; }
    &:-moz-placeholder { color:#DDD; }
    &::-moz-placeholder { color:#DDD; }
    &:-ms-input-placeholder { color:#DDD; }
  }

  &::-webkit-input-placeholder {
     color: #BBB;
     transition:color 0.5s ease;
  }

  &:-moz-placeholder { /* Firefox 18- */
     color: #BBB;  
     transition:color 0.5s ease;
  }

  &::-moz-placeholder {  /* Firefox 19+ */
     color: #BBB;  
     transition:color 0.5s ease;
  }

  &:-ms-input-placeholder {  
     color: #BBB;  
     transition:color 0.5s ease;
  }
}

有没有办法使用SASS或指南针来缩短/消除它?

1 个答案:

答案 0 :(得分:5)

您可以做的最好的事情是将占位符抽象为mixin:

@mixin placeholder {
  &::-webkit-input-placeholder {
     @content;
  }

  &:-moz-placeholder { /* Firefox 18- */
     @content;
  }

  &::-moz-placeholder {  /* Firefox 19+ */
     @content;
  }

  &:-ms-input-placeholder {  
     @content;
  }
}

input {
  background-image:url(search.png);
  background-repeat:no-repeat;
  background-size:20px 20px;
  background-position-x:12px;
  background-position-y:10px;
  background-color:#6E597E;
  box-shadow:0 0 5px #333 inset;
  border-radius:15px;
  border:0;
  padding:8px 10px 10px 45px;
  font-size:20px;
  font-weight:300;
  font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
  color:#BBB;
  width:100%;
  transition:all 0.5s ease;
  &:focus {
    outline:none;
    box-shadow:0 0 10px #333 inset;
    background-color:#85699A;
    color:#EEE;

    @include placeholder { color:#DDD; }
  }

  @include placeholder {  
     color: #BBB;  
     transition:color 0.5s ease;
  }
}