UserscriptAPIDom

https://gitee.com/liangjiancang/userscript/tree/master/lib/UserscriptAPI

当前为 2021-09-06 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/431998/967886/UserscriptAPIDom.js

  1. /**
  2. * UserscriptAPIDom
  3. *
  4. * 依赖于 `UserscriptAPI`。
  5. * @version 1.0.0.20210906
  6. * @author Laster2800
  7. * @see {@link https://gitee.com/liangjiancang/userscript/tree/master/lib/UserscriptAPI UserscriptAPI}
  8. */
  9. class UserscriptAPIDom {
  10. /**
  11. * @param {UserscriptAPI} api `UserscriptAPI`
  12. */
  13. constructor(api) {
  14. this.api = api
  15. }
  16.  
  17. /**
  18. * 初始化 urlchange 事件
  19. * @see {@link https://stackoverflow.com/a/52809105 How to detect if URL has changed after hash in JavaScript}
  20. */
  21. initUrlchangeEvent() {
  22. if (!history._urlchangeEventInitialized) {
  23. const urlEvent = () => {
  24. const event = new Event('urlchange')
  25. // 添加属性,使其与 Tampermonkey urlchange 保持一致
  26. event.url = location.href
  27. return event
  28. }
  29. history.pushState = (f => function pushState() {
  30. const ret = f.apply(this, arguments)
  31. window.dispatchEvent(new Event('pushstate'))
  32. window.dispatchEvent(urlEvent())
  33. return ret
  34. })(history.pushState)
  35. history.replaceState = (f => function replaceState() {
  36. const ret = f.apply(this, arguments)
  37. window.dispatchEvent(new Event('replacestate'))
  38. window.dispatchEvent(urlEvent())
  39. return ret
  40. })(history.replaceState)
  41. window.addEventListener('popstate', () => {
  42. window.dispatchEvent(urlEvent())
  43. })
  44. history._urlchangeEventInitialized = true
  45. }
  46. }
  47.  
  48. /**
  49. * 添加样式
  50. * @param {string} css 样式
  51. * @param {HTMLDocument} [doc=document] 文档
  52. * @returns {HTMLStyleElement} `<style>`
  53. */
  54. addStyle(css, doc = document) {
  55. const api = this.api
  56. const style = doc.createElement('style')
  57. style.setAttribute('type', 'text/css')
  58. style.className = `${api.options.id}-style`
  59. style.appendChild(doc.createTextNode(css))
  60. const parent = doc.head || doc.documentElement
  61. if (parent) {
  62. parent.appendChild(style)
  63. } else { // 极端情况下会出现,DevTools 网络+CPU 双限制可模拟
  64. api.wait?.waitForConditionPassed({
  65. condition: () => doc.head || doc.documentElement,
  66. timeout: 0,
  67. }).then(parent => parent.appendChild(style))
  68. }
  69. return style
  70. }
  71.  
  72. /**
  73. * 设定元素位置,默认设定为绝对居中
  74. *
  75. * 要求该元素此时可见且尺寸为确定值(一般要求为块状元素)。
  76. * @param {HTMLElement} target 目标元素
  77. * @param {Object} [config] 配置
  78. * @param {string} [config.position='fixed'] 定位方式
  79. * @param {string} [config.top='50%'] `style.top`
  80. * @param {string} [config.left='50%'] `style.left`
  81. */
  82. setPosition(target, config) {
  83. config = {
  84. position: 'fixed',
  85. top: '50%',
  86. left: '50%',
  87. ...config,
  88. }
  89. target.style.position = config.position
  90. const style = window.getComputedStyle(target)
  91. const top = (parseFloat(style.height) + parseFloat(style.paddingTop) + parseFloat(style.paddingBottom)) / 2
  92. const left = (parseFloat(style.width) + parseFloat(style.paddingLeft) + parseFloat(style.paddingRight)) / 2
  93. target.style.top = `calc(${config.top} - ${top}px)`
  94. target.style.left = `calc(${config.left} - ${left}px)`
  95. }
  96.  
  97. /**
  98. * 处理 HTML 元素的渐显和渐隐
  99. *
  100. * * 读取 `target` 上的 `fadeInDisplay` 来设定渐显开始后的 `display` 样式。若没有设定:
  101. * * 若当前 `display` 与 `fadeOutDisplay` 不同,默认值为当前 `display`。
  102. * * 若当前 `display` 与 `fadeOutDisplay` 相同,默认值为 `block`。
  103. *
  104. * * 读取 `target` 上的 `fadeOutDisplay` 来设定渐隐开始后的 `display` 样式,默认值为 `none`。
  105. *
  106. * * 读取 `target` 上的 `fadeInTime` 和 `fadeOutTime` 属性来设定渐显和渐隐时间,它们应为以 `ms` 为单位的 `number`;否则,`target.style.transition` 上关于时间的设定应该与 `api.options.fadeTime` 保持一致。
  107. *
  108. * * 读取 `target` 上的 `fadeInFunction` 和 `fadeOutFunction` 属性来设定渐变效果(默认 `ease-in-out`),它们应为符合 `transition-timing-function` 的 `string`。
  109. *
  110. * * 读取 `target` 上的 `fadeInNoInteractive` 和 `fadeOutNoInteractive` 属性来设定渐显和渐隐期间是否禁止交互,它们应为 `boolean`。
  111. * @param {boolean} inOut 渐显/渐隐
  112. * @param {HTMLElement} target HTML 元素
  113. * @param {() => void} [callback] 渐显/渐隐完成的回调函数
  114. */
  115. fade(inOut, target, callback) {
  116. const api = this.api
  117. let transitionChanged = false
  118. const fadeId = new Date().getTime() // 等同于当前时间戳,其意义在于保证对于同一元素,后执行的操作必将覆盖前的操作
  119. const fadeOutDisplay = target.fadeOutDisplay ?? 'none'
  120. target._fadeId = fadeId
  121. if (inOut) { // 渐显
  122. let displayChanged = false
  123. if (typeof target.fadeInTime == 'number' || target.fadeInFunction) {
  124. target.style.transition = `opacity ${target.fadeInTime ?? api.options.fadeTime}ms ${target.fadeInFunction ?? 'ease-in-out'}`
  125. transitionChanged = true
  126. }
  127. if (target.fadeInNoInteractive) {
  128. target.style.pointerEvents = 'none'
  129. }
  130. const originalDisplay = window.getComputedStyle(target).display
  131. let fadeInDisplay = target.fadeInDisplay
  132. if (!fadeInDisplay) {
  133. if (originalDisplay != fadeOutDisplay) {
  134. fadeInDisplay = originalDisplay
  135. } else {
  136. fadeInDisplay = 'block'
  137. }
  138. }
  139. if (originalDisplay != fadeInDisplay) {
  140. target.style.display = fadeInDisplay
  141. displayChanged = true
  142. }
  143. setTimeout(() => {
  144. let success = false
  145. if (target._fadeId <= fadeId) {
  146. target.style.opacity = '1'
  147. success = true
  148. }
  149. setTimeout(() => {
  150. callback?.(success)
  151. if (target._fadeId <= fadeId) {
  152. if (transitionChanged) {
  153. target.style.transition = ''
  154. }
  155. if (target.fadeInNoInteractive) {
  156. target.style.pointerEvents = ''
  157. }
  158. }
  159. }, target.fadeInTime ?? api.options.fadeTime)
  160. }, displayChanged ? 10 : 0) // 此处的 10ms 是为了保证修改 display 后在浏览器上真正生效;按 HTML5 定义,浏览器需保证 display 在修改后 4ms 内生效,但实际上大部分浏览器貌似做不到,等个 10ms 再修改 opacity
  161. } else { // 渐隐
  162. if (typeof target.fadeOutTime == 'number' || target.fadeOutFunction) {
  163. target.style.transition = `opacity ${target.fadeOutTime ?? api.options.fadeTime}ms ${target.fadeOutFunction ?? 'ease-in-out'}`
  164. transitionChanged = true
  165. }
  166. if (target.fadeOutNoInteractive) {
  167. target.style.pointerEvents = 'none'
  168. }
  169. target.style.opacity = '0'
  170. setTimeout(() => {
  171. let success = false
  172. if (target._fadeId <= fadeId) {
  173. target.style.display = fadeOutDisplay
  174. success = true
  175. }
  176. callback?.(success)
  177. if (success) {
  178. if (transitionChanged) {
  179. target.style.transition = ''
  180. }
  181. if (target.fadeOutNoInteractive) {
  182. target.style.pointerEvents = ''
  183. }
  184. }
  185. }, target.fadeOutTime ?? api.options.fadeTime)
  186. }
  187. }
  188.  
  189. /**
  190. * 为 HTML 元素添加 `class`
  191. * @param {HTMLElement} el 目标元素
  192. * @param {...string} className `class`
  193. */
  194. addClass(el, ...className) {
  195. el.classList?.add(...className)
  196. }
  197.  
  198. /**
  199. * 为 HTML 元素移除 `class`
  200. * @param {HTMLElement} el 目标元素
  201. * @param {...string} [className] `class`,未指定时移除所有 `class`
  202. */
  203. removeClass(el, ...className) {
  204. if (className.length > 0) {
  205. el.classList?.remove(...className)
  206. } else if (el.className) {
  207. el.className = ''
  208. }
  209. }
  210.  
  211. /**
  212. * 判断 HTML 元素类名中是否含有 `class`
  213. * @param {HTMLElement} el 目标元素
  214. * @param {string | string[]} className `class`,支持同时判断多个
  215. * @param {boolean} [and] 同时判断多个 `class` 时,默认采取 `OR` 逻辑,是否采用 `AND` 逻辑
  216. * @returns {boolean} 是否含有 `class`
  217. */
  218. containsClass(el, className, and = false) {
  219. if (el.classList) {
  220. const trim = clz => clz.startsWith('.') ? clz.slice(1) : clz
  221. if (className instanceof Array) {
  222. if (and) {
  223. for (const c of className) {
  224. if (!el.classList.contains(trim(c))) {
  225. return false
  226. }
  227. }
  228. return true
  229. } else {
  230. for (const c of className) {
  231. if (el.classList.contains(trim(c))) {
  232. return true
  233. }
  234. }
  235. return false
  236. }
  237. } else {
  238. return el.classList.contains(trim(className))
  239. }
  240. }
  241. return false
  242. }
  243.  
  244. /**
  245. * 判断 HTML 元素是否为 `fixed` 定位,或其是否在 `fixed` 定位的元素下
  246. * @param {HTMLElement} el 目标元素
  247. * @param {HTMLElement} [endEl] 终止元素,当搜索到该元素时终止判断(不会判断该元素)
  248. * @returns {boolean} HTML 元素是否为 `fixed` 定位,或其是否在 `fixed` 定位的元素下
  249. */
  250. isFixed(el, endEl) {
  251. while (el && el != endEl) {
  252. if (window.getComputedStyle(el).position == 'fixed') {
  253. return true
  254. }
  255. el = el.offsetParent
  256. }
  257. return false
  258. }
  259. }
  260.  
  261. /* global UserscriptAPI */
  262. { UserscriptAPI.registerModule('dom', UserscriptAPIDom) }

QingJ © 2025

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