debounce

當執行某些event時(比如說scroll event),瀏覽器會執行很多次,這時可以用debounce function,限制他只能每xx毫秒執行一次,以節省效能

未使用debounce時

function goScroll(){
  console.count('gogogo');
}

window.addEventListener('scroll', goScroll);

//此時滑動螢幕捲軸,會發現後台被執行了很多次

使用debounce function減輕效能負擔

function debounce(func, wait = 20, immediate = true) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
}

function goScroll(){
  console.count('gogogo');
}

window.addEventListener('scroll', debounce(goScroll, 50));
//debounce的第2個參數可以定義多久毫秒執行1次,若沒填的話此範例預設是每20秒執行1次。

【CSS】卡片翻面效果

<div class="photo">
    <div class="front">第一張卡片</div>
    <div class="back">第二張卡片</div>
</div>
.front {
  width: 300px;
  height: 350px;
  backface-visibility: hidden;
  transition: 0.6s;
  transform-style: preserve-3d;
  position: absolute;
  top: 0;
  left: 0;
  background-color: red;
}
.back {
  width: 300px;
  height: 350px;
  backface-visibility: hidden;
  transition: 0.6s;
  transform-style: preserve-3d;
  position: absolute;
  top: 0;
  left: 0;
  transform: rotateY(-180deg);
  background-color: green;
}
.photo:hover .back {
  transform: rotateY(0deg);
}
.photo:hover .front {
  transform: rotateY(180deg);
}

Class add and remove

此寫法為達成以下目的(常應用於選單收合)

  • A開啟時,點了B,打開B時要順便收起A
  • A開啟時,點了A,要收起A
.box apple
.box orange
.box grape
.box blue
.box gray
.box
 width: 200px
 height: 100px
 background-color: #eee
 text-align: center
 line-height: 100px
 transition-duration: 0.5s
 
.box.teal
 background-color: teal
 color: #fff
const boxes=document.querySelectorAll(".box");

boxes.forEach(box => box.addEventListener("click", checkall)
)

function checkall(){
 const nowTeal=document.querySelector(".teal");
 
 if(nowTeal){
  nowTeal.classList.remove("teal");
 }
 
 if(nowTeal==this){
  this.classList.remove("teal");
 }else{
   this.classList.add("teal");
 }

}