shubiao.js 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. var CURSOR;
  2. Math.lerp = (a, b, n) => (1 - n) * a + n * b;
  3. const getStyle = (el, attr) => {
  4. try {
  5. return window.getComputedStyle
  6. ? window.getComputedStyle(el)[attr]
  7. : el.currentStyle[attr];
  8. } catch (e) {}
  9. return "";
  10. };
  11. class Cursor {
  12. constructor() {
  13. this.pos = {curr: null, prev: null};
  14. this.pt = [];
  15. this.create();
  16. this.init();
  17. this.render();
  18. }
  19. move(left, top) {
  20. this.cursor.style["left"] = `${left}px`;
  21. this.cursor.style["top"] = `${top}px`;
  22. }
  23. create() {
  24. if (!this.cursor) {
  25. this.cursor = document.createElement("div");
  26. this.cursor.id = "cursor";
  27. this.cursor.classList.add("hidden");
  28. document.body.append(this.cursor);
  29. }
  30. var el = document.getElementsByTagName('*');
  31. for (let i = 0; i < el.length; i++)
  32. if (getStyle(el[i], "cursor") == "pointer")
  33. this.pt.push(el[i].outerHTML);
  34. document.body.appendChild((this.scr = document.createElement("style")));
  35. // 这里改变鼠标指针的颜色 由svg生成
  36. this.scr.innerHTML = `* {cursor: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8' width='8px' height='8px'><circle cx='4' cy='4' r='4' opacity='.5'/></svg>") 4 4, auto}`;
  37. }
  38. refresh() {
  39. this.scr.remove();
  40. this.cursor.classList.remove("hover");
  41. this.cursor.classList.remove("active");
  42. this.pos = {curr: null, prev: null};
  43. this.pt = [];
  44. this.create();
  45. this.init();
  46. this.render();
  47. }
  48. init() {
  49. document.onmouseover = e => this.pt.includes(e.target.outerHTML) && this.cursor.classList.add("hover");
  50. document.onmouseout = e => this.pt.includes(e.target.outerHTML) && this.cursor.classList.remove("hover");
  51. document.onmousemove = e => {(this.pos.curr == null) && this.move(e.clientX - 8, e.clientY - 8); this.pos.curr = {x: e.clientX - 8, y: e.clientY - 8}; this.cursor.classList.remove("hidden");};
  52. document.onmouseenter = e => this.cursor.classList.remove("hidden");
  53. document.onmouseleave = e => this.cursor.classList.add("hidden");
  54. document.onmousedown = e => this.cursor.classList.add("active");
  55. document.onmouseup = e => this.cursor.classList.remove("active");
  56. }
  57. render() {
  58. if (this.pos.prev) {
  59. this.pos.prev.x = Math.lerp(this.pos.prev.x, this.pos.curr.x, 0.15);
  60. this.pos.prev.y = Math.lerp(this.pos.prev.y, this.pos.curr.y, 0.15);
  61. this.move(this.pos.prev.x, this.pos.prev.y);
  62. } else {
  63. this.pos.prev = this.pos.curr;
  64. }
  65. requestAnimationFrame(() => this.render());
  66. }
  67. }
  68. (() => {
  69. CURSOR = new Cursor();
  70. // 需要重新获取列表时,使用 CURSOR.refresh()
  71. })();