読者です 読者をやめる 読者になる 読者になる

みかづきブログ その3

3ヶ月つづけてみました。

CSSでおしゃれな切り替えボタンをつくる

アニメーションをつけてみました。

DEMO

See the Pen Button by kimmy (@kimmy) on CodePen.


HTML

<div class="box">
  <ul data-index="0" data-length="2" class="btns">
    <li data-index="0" class="btn">LEFT</li>
    <li data-index="1" class="btn">RIGHT</li>
  </ul>
  <ul data-index="0" data-length="3" class="btns">
    <li data-index="0" class="btn">LEFT</li>
    <li data-index="1" class="btn">CENTER</li>
    <li data-index="2" class="btn">RIGHT</li>
  </ul>
</div>

SCSS

.box {
  position: absolute;
  top: 0; bottom: 0;
  left: 0; right: 0;
  margin: auto;
  width: 600px; height: 150px;
}

.btns {
  position: relative;
  margin: auto;
  height: 50px;
  overflow: hidden;
  user-select: none;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  
  &[data-length="2"] {
    width: 400px;
    
    &:before {
      width: 50%;
    }
    
    &:after {
      position: absolute;
      top: 0; bottom: 0;
      left: 0; right: 0;
      width: 1px;
      background: #000;
    }
    
    &[data-index="0"] {
      &:before {
        left: 0;
      }
    }
    
    &[data-index="1"] {
      &:before {
        left: 50%;
      }
    }
  }
  
  &[data-length="3"] {
    margin-top: 50px;
    width: 600px;
    
    &:before {
      width: 33.33%;
    }
    
    &:after {
      margin: auto;
      border-left: solid 1px #000;
      border-right: solid 1px #000;
      width: 33.33%;
    }
    
    &[data-index="0"] {
      &:before {
        left: 0;
      }
    }
    
    &[data-index="1"] {
      &:before {
        left: 33.33%;
      }
    }
    
    &[data-index="2"] {
      &:before {
        left: 66.66%;
      }
    }
  }
  
  .btn {
    float: left;
    width: 200px; height: 50px;
    font: bold 34px "Helvetica";
    line-height: 50px;
    text-align: center;
    cursor: pointer;
    transition: color .15s ease-in-out;
  }
  
  &:before {
    display: block;
    position: absolute;
    top: 0; bottom: 0;
    content: "";
    background: #7f7f7f;
    z-index: -1;
    transition: left .15s ease-in-out;
  }

    &:after {
      display: block;
      margin: auto;
      height: 50px;
      content: "";
    }
  
  &[data-index="0"] {
    [data-index="0"] {
      color : #fff;
    }
  }
  
  &[data-index="1"] {    
    [data-index="1"] {
      color : #fff;
    }
  }
  
  &[data-index="2"] {
    [data-index="2"] {
      color : #fff;
    }
  }
}

JavaScript

var btns = document.querySelectorAll(".btns");

for (let i = 0, length = btns.length; i < length; ++i) {
  btns[i].addEventListener("click", function(evt) {
    var index = evt.target.getAttribute("data-index");

    this.setAttribute("data-index", index);
  });
}