CommonUtils

通用工具。

目前为 2020-03-16 提交的版本。查看 最新版本

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/398010/781167/CommonUtils.js

  1. // ==UserScript==
  2. // @name CommonUtils
  3. // @name:zh CommonUtils
  4. // @name:zh-CN CommonUtils
  5. // @name:en CommonUtils
  6. // @description 通用工具。
  7. // @description:zh 通用工具。
  8. // @description:zh-CN 通用工具。
  9. // @description:en Common Utils.
  10. // @namespace https://greasyfork.org/zh-CN/users/331591
  11. // @version 1.0.0
  12. // @author Hale Shaw
  13. // @homepage https://greasyfork.org/zh-CN/scripts/398010
  14. // @supportURL https://greasyfork.org/zh-CN/scripts/398010/feedback
  15. // @icon https://greasyfork.org/assets/blacklogo16-bc64b9f7afdc9be4cbfa58bdd5fc2e5c098ad4bca3ad513a27b15602083fd5bc.png
  16. // @match https://greasyfork.org/*
  17. // @license AGPL-3.0-or-later
  18. // @compatible Chrome
  19. // @run-at document-idle
  20. // @grant none
  21. // ==/UserScript==
  22.  
  23. /**
  24. * check whether the element is valid by id.
  25. * @param {String} id element id.
  26. */
  27. function isValidById(id) {
  28. if (document.getElementById(id)) {
  29. return true;
  30. } else {
  31. return false;
  32. }
  33. }
  34.  
  35. /**
  36. * check whether the element is valid by class name.
  37. * @param {String} className element class name.
  38. */
  39. function isValidByClassName(className) {
  40. if (document.getElementsByClassName(className) && document.getElementsByClassName(className)[0] !== undefined) {
  41. return true;
  42. } else {
  43. return false;
  44. }
  45. }
  46.  
  47. /**
  48. * 扩展Date原型,将Date转化为指定格式的String.
  49. * 年(y)可以用 1-4 个占位符,
  50. * 月(M)、日(d)、小时(H)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
  51. * 毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
  52. * 例子:
  53. * (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
  54. * (new Date()).Format("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.182
  55. * @param {String} fmt fotmat 格式字符串.
  56. */
  57. Date.prototype.format = function (fmt) {
  58. var ret;
  59. var opt = {
  60. "y+": this.getFullYear().toString(),
  61. "M+": (this.getMonth() + 1).toString(),
  62. "d+": this.getDate().toString(),
  63. "H+": this.getHours().toString(),
  64. "m+": this.getMinutes().toString(),
  65. "s+": this.getSeconds().toString(), //秒
  66. "q+": (Math.floor((this.getMonth() + 3) / 3)).toString(), //季度
  67. "S": this.getMilliseconds().toString() //毫秒
  68. // 有其他格式化字符需求可以继续添加,必须转化成字符串
  69. };
  70. for (var k in opt) {
  71. ret = new RegExp("(" + k + ")").exec(fmt);
  72. if (ret) {
  73. fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
  74. }
  75. }
  76. return fmt;
  77. }