1. 程式人生 > 其它 >常用的前端方法封裝1

常用的前端方法封裝1

滑鼠在元素上移進移出事件

<body>

<img class="viewImg" src="./1.jpg" alt="">

</body>

<script>

// 獲取到所有圖片 let imags = document.querySelectorAll(".viewImg"); // 迴圈新增滑鼠事件 imags.forEach((item) => { // 滑鼠移動進來 item.addEventListener("mouseover", function() { console.log("進來"); }); // 滑鼠移動出去 item.addEventListener("mouseout", function() { console.log("出來"); }); });

</script>

如何確認父元素是否包含子元素

function elementContains(parent, child) {
  return parent !== child && parent.contains(child);
}
// Examples
elementContains(
  document.querySelector("head"),
  document.querySelector("title")
); // true
elementContains(document.querySelector("body"), document.querySelector("body
")); // false

獲取當前 URL

const currentURL = () => window.location.href;

// Example
currentURL(); // "https://google.com"

判斷裝置型別

const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
    navigator.userAgent
  )
    ? "Mobile"
    : "Desktop";

// Desktop:桌面;Mobile:手機
console.log(detectDeviceType()); // "Mobile" or "Desktop"

獲取兩個日期之間的天數間隔

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600 * 24);

// Example
getDaysDiffBetweenDates(new Date("2021-12-13"), new Date("2021-12-22")); // 9

獲取 URL 的引數

const getURLParameters = (url) =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => (
      (a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a
    ),
    {}
  );

// Examples
console.log(getURLParameters("https://baidu.com?n=小明&a=18"));
// {n: "小明", a: "18"}

判斷某個元素上是否存在某個樣式類

<main>
  <div class="title block">標題</div>
</main>
<script>
  function hasClass(el, className) {
    let els = document.querySelector(el);
    return els.classList.contains(className);
  }
  // 判斷某個元素上是否存在某個樣式類
  console.log(hasClass("main>div", "title")); // true

  console.log(hasClass("main>div", "rightTitle")); // false
</script>

批量隱藏指定元素

function hideAll(tagname) {
  let els = document.querySelectorAll(tagname);
  [...els].forEach((item) => {
    item.style.display = "none";
  });
}
// 隱藏所有 b 標籤
hideAll("b");

切換元素的類

// 切換元素的類
const toggleClass = (el, className) => el.classList.toggle(className);

// 如果該元素原本有success類,則刪除這個類,如果沒有則新增success
toggleClass(document.querySelector("div"), "success");

添加回到頂部按鈕

<style>
    /* 元素固定在右下角樣式 */
.top {
  position: fixed;
  right: 10px;
  bottom: 20px;
}
</style>
<body>
  <div style="height: 999px;" id="center_box_lefts">
    <div style="height: 30px;">佔位符</div>
    <div style="height: 30px;">佔位符</div>
    <div style="height: 30px;">佔位符</div>
    <div style="height: 30px;">佔位符</div>
  </div>
  <button class="top" onclick="totop()">回到頂部</button>
  <script>
    // 監聽滾動條位置
    window.addEventListener("scroll", () => {
      // pageYOffset:表示文件在視窗垂直方向滾動的畫素
      console.log(window.pageYOffset);
      if (window.pageYOffset > 270) {
        document.querySelector(".top").style.display = "block";
      } else {
        document.querySelector(".top").style.display = "none";
      }
    });

    // 返回頂部方法
    const scrollToTop = () => {
      const c = document.documentElement.scrollTop || document.body.scrollTop;
      if (c > 0) {
        window.requestAnimationFrame(scrollToTop);
        window.scrollTo(0, c - c / 8);
      }
    };
    function totop() {
      scrollToTop();
    }
    // Example
  </script>
</body>

確認指定元素是否在視口可見

<style>
  #box {
    width: 200px;
    height: 200px;
    background-color: red;
    margin-top: 50px;
  }

  #box2 {
    width: 200px;
    height: 200px;
    background-color: green;
    margin-top: 300px;
  }
</style>

<body>
  <div id="box"></div>
  <div id="box2"></div>
  <script>
    const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
      const { top, left, bottom, right } = el.getBoundingClientRect();
      const { innerHeight, innerWidth } = window;
      return partiallyVisible
        ? ((top > 0 && top < innerHeight) ||
            (bottom > 0 && bottom < innerHeight)) &&
            ((left > 0 && left < innerWidth) ||
              (right > 0 && right < innerWidth))
        : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
    };
    let el = document.querySelector("#box");
    let el2 = document.querySelector("#box2");

    // true 完全可見
    console.log(elementIsVisibleInViewport(el));
    // false 部分可見或不可見
    console.log(elementIsVisibleInViewport(el2));
  </script>
</body>

監聽頁面寬高

function watchSize() {
  let windowSize = {};
  window.addEventListener("resize", () => {
    windowSize = {
      innerHeight: this.innerHeight,
      innerWidth: this.innerWidth,
    };
    console.log(windowSize); // {innerHeight: 625, innerWidth: 232}
  });
  return windowSize;
}
watchSize();

獲取格式化後的日期

let date = new Date();
//
console.log(date.getFullYear());
//
console.log(date.getMonth() + 1);
//
console.log(date.getDate());
//
console.log(date.getHours());
//
console.log(date.getMinutes());
//
console.log(date.getSeconds());

function dateFormat(date, format = "YYYY-MM-DD HH:mm:ss") {
  const config = {
    YYYY: date.getFullYear(),
    MM:
      date.getMonth() + 1 < 10
        ? `0${date.getMonth() + 1}`
        : date.getMonth() + 1,
    DD: date.getDate(),
    HH: date.getHours(),
    mm: date.getMinutes(),
    ss: date.getSeconds(),
  };
  for (let key in config) {
    format = format.replace(key, config[key]);
  }
  return format;
}

// 可以根據指定的格式返回日期
console.log(dateFormat(date, "YYYY-MM-DD HH:mm:ss"));