H2P: utils

utils

目前为 2020-09-13 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/411278/847389/H2P%3A%20utils.js

// ==UserScript==
// @name        H2P: utils
// @namespace   http://tampermonkey.net/
// @version     0.0.4
// @icon        http://www.douyutv.com/favicon.ico
// @description utils
// @author      H2P
// @compatible  chrome
// ==/UserScript==

((w) => {
  'use strict';

  /**
   * 在字符串前(后)添加 0
   * @param {String} s
   * @param {Number} len 
   * @param {Boolean} isAddFront 
   */
  function add0(s = '', len = 0, isAddFront = true) {
    s = s.toString();
    while (s.length < len) { s = isAddFront ? '0' + s : s + '0'; }
    return s;
  }

  function $$() {
    /**
     * 返回毫秒
     * @param {Number} num 
     */
    this.timeMS = (num = 0) => {
      num = Number.parseInt(num);
      return num < 946684800000 ? num * 1000 : num;
    }

    /**
     * localStorage 相关操作
     */
    this.LS = {
      init: (itemKey = '', itemPre = {}) => {
        let item = Object.assign({}, itemPre, this.get(itemKey));
        for (let key in item) { if (!(key in itemPre)) { delete item[key]; } }
        localStorage.removeItem(itemKey);
        localStorage.setItem(itemKey, JSON.stringify(item));
        return item;
      },
      set: (itemKey = '', item = {}) => { localStorage.setItem(itemKey, JSON.stringify(item)); },
      get: (itemKey = '') => JSON.parse(localStorage.getItem(itemKey)) || {},
      remove: (itemKey = '') => { localStorage.removeItem(itemKey); }
    }


    this.HMS = (time = 0) => {
      time = this.timeMS(time);
      let h = Number.parseInt(time / 3600000);
      let m = Number.parseInt(time % 3600000 / 60000);
      let s = Number.parseInt(time % 3600000 % 60000 / 1000);
      return {
        h: add0(h, 2),
        m: add0(m, 2),
        s: add0(s, 2),
      }
    }
  }

  // return millisecond
  Date.prototype.$timems = Date.prototype.getTime;
  // return second
  Date.prototype.$times = function() { return Number.parseInt(this.getTime() / 1000); }
  // format time: yyyy-MM-dd hh-mm-ss
  Date.prototype.$formatTime = function() { return `${this.getFullYear()}-${add0(this.getMonth() + 1, 2)}-${add0(this.getDate(), 2)} ${add0(this.getHours(), 2)}:${add0(this.getMinutes(), 2)}:${add0(this.getSeconds(), 2)}`; }
  // format date: yyyy-MM-dd
  Date.prototype.$formatDate = function() { return `${this.getFullYear()}-${add0(this.getMonth() + 1, 2)}-${add0(this.getDate(), 2)}`; } 

  /**
   * 根据 xpath 查询元素
   * @param {String} xpath 
   * @param {Boolean} queryOneElement 
   */
  w.$H2P = (xpath = 'body', queryOneElement = true) => queryOneElement ? document.querySelector(xpath) : Array.from(document.querySelectorAll(xpath));

  w.$$ = new $$();
})(window);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址