html-utils

utils for DOM manipulation and fetching info of a webpage

当前为 2016-08-30 提交的版本,查看 最新版本

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

  1. // ==UserScript==
  2. // @name html-utils
  3. // @name:de html-utils
  4. // @namespace dannysaurus.camamba
  5. // @version 0.1
  6. // @license MIT License
  7. // @description utils for DOM manipulation and fetching info of a webpage
  8. // @description:de utils for DOM manipulation and fetching info of a webpage
  9. // ==/UserScript==
  10. /*
  11. grant GM_xmlhttpRequest
  12. require https://gf.qytechs.cn/scripts/22752-object-utils/code/object-utils.js
  13. */
  14.  
  15. var LIB = LIB || {};
  16. /**
  17. * Html Elements
  18. * @type {{Element, Button, Div, Input, Checkbox, Label, TextArea, Option, Select}}
  19. */
  20. LIB.htmlUtils = (function() {
  21. 'use strict';
  22. var objectUtils = LIB.objectUtils;
  23. var keeper = new objectUtils.Keeper();
  24. /**
  25. * Adds a HTML child node to a HTML parent node.
  26. * @param {HtmlElement|Element} parent - The html parent node
  27. * @param {HtmlElement|Element} child - The html child Element to be connected to the parent node
  28. * @param {boolean} [asFirstChild] - <code>true</code> to have the child be added as the first child before any other child
  29. */
  30. var connectParentChild = function(parent, child, asFirstChild) {
  31. var elParent = parent instanceof Element ? parent.domElement : parent;
  32. var elChild = child instanceof Element ? child.domElement : child;
  33. if (asFirstChild && elParent.hasChildNodes()) {
  34. elParent.insertBefore(elChild, elParent.firstChild);
  35. } else {
  36. elParent.appendChild(elChild);
  37. }
  38. };
  39. /**
  40. * Removes a HTML child element from a HTML parent node.
  41. * @param {HTMLElement} parent - The parent node
  42. * @param {HTMLElement} elChild - The child node to be removed of the parent element
  43. */
  44. var disconnectParentChild = function(parent, elChild) {
  45. var elParent = parent instanceof Element ? parent.domElement : parent;
  46. elParent.removeChild(elChild);
  47. };
  48. /**
  49. * Removes all HTML children from a parent node.
  50. * @param {HTMLElement} parent - The HTML parent node
  51. */
  52. var removeAllChildren = function(parent) {
  53. var elParent = parent instanceof Element ? parent.domElement : parent;
  54. while (elParent.hasChildNodes()) {
  55. elParent.removeChild(elParent.firstChild);
  56. }
  57. };
  58.  
  59. /**
  60. * Sorts options of a html 'select' element from a certain property of the option (e.g. text or value).
  61. * @param {HTMLElement|Element} select - The Select Element to be sorted
  62. * @param {string} [property=text] - The Name of the property from wich the option should be compared like <code>value</code> or <code>text</code>.
  63. * @param {boolean} [isOrderDescending] - <code>true</code> to reverse the sort order.
  64. */
  65. var sortSelectBy = function(select, property, isOrderDescending) {
  66. var elSelect = select instanceof Element ? select.domElement : select;
  67. var propertyName = property || 'text';
  68. var sortOptions = [];
  69. // options to array
  70. for (var i = 0; i <= select.length - 1; i++) {
  71. var option = select[i];
  72. sortOptions.push({
  73. value:option.value,
  74. text:option.text,
  75. selected:option.selected
  76. });
  77. }
  78. // sort array
  79. sortOptions.sort(function (a, b) {
  80. if (a[propertyName] < b[propertyName]) { return isOrderDescending ? 1 : -1; }
  81. if (a[propertyName] > b[propertyName]) { return isOrderDescending ? -1 : 1; }
  82. return 0;
  83. });
  84. // array to options
  85. sortOptions.forEach(function (opt, i) {
  86. select[i].text = opt.text;
  87. select[i].value = opt.value;
  88. select[i].selected = opt.selected;
  89. });
  90. };
  91.  
  92. /**
  93. * Wrapper for any type of HTML element.
  94. * @param {string} tagName - The type of element to be created and value of the <code>nodeName</code> attribute
  95. * @param {string} [id] - The value for the <code>id</code> attribute
  96. * @param {string} [className] - The value for the <code>class</code> attribute
  97. * @constructor
  98. */
  99. function Element(tagName, id, className) {
  100. if (!(this instanceof Element)) {
  101. return new Element(tagName, id, className);
  102. }
  103. var domElement = document.createElement(tagName);
  104. Object.defineProperty(this, "domElement", {
  105. get: function() { return domElement },
  106. configurable: true, enumerable: true
  107. });
  108. if (typeof id !== 'undefined') {
  109. this.domElement.id = id;
  110. }
  111. if (typeof className !== 'undefined') {
  112. this.domElement.className = className;
  113. }
  114. }
  115. Element.prototype = {
  116. constructor: Element,
  117. /**
  118. * Adds this HTML element to a parent node HTML element.
  119. * It will be added as the last child of the node.
  120. * @param {HTMLElement|Element} elParent - The parent HTML node element
  121. */
  122. addAsLastChild : function(elParent) {
  123. var parent = elParent instanceof Element ? elParent.domElement : elParent;
  124. connectParentChild(elParent, this.domElement, false);
  125. },
  126. /**
  127. * Adds this HTML element to a parent node HTML element.
  128. * It will be added as the first child of the node.
  129. * @param {HTMLElement|Element} elParent - The parent HTML node element
  130. */
  131. addAsFirstChild : function(elParent) {
  132. var parent = elParent instanceof Element ? elParent.domElement : elParent;
  133. connectParentChild(elParent, this, true);
  134. },
  135. /**
  136. * Adds this HTML element to a parent node HTML element.
  137. * All children elements will be removed and replaced with this node.
  138. * @param {HTMLElement|Element} elParent - The parent HTML node element
  139. */
  140. addAsOnlyChild : function(elParent) {
  141. var parent = elParent instanceof Element ? elParent.domElement : elParent;
  142. removeAllChildren(elParent);
  143. connectParentChild(elParent, this);
  144. },
  145. /**
  146. * Appends Html node elements to this node as their last children.
  147. * @param {...HTMLElement|Element} elements - Html elements to be added as children.
  148. */
  149. appendChildren : function(elements) {
  150. for (var i = 0; i <= arguments.length - 1; i++) {
  151. var child = arguments[i];
  152. this.domElement.appendChild(child instanceof Element ? child.domElement : child);
  153. }
  154. },
  155. /**
  156. * Adds Html node Elements to this node as their new children.
  157. * All current children elements will be removed and replaced with the new children.
  158. * @param {...HTMLElement} [elements] Html elements to be added as children
  159. * No argument will only remove all children.
  160. */
  161. setChildren : function(elements) {
  162. removeAllChildren(this);
  163. for (var i = 0; i <= arguments.length - 1; i++) {
  164. connectParentChild(this, arguments[i]);
  165. }
  166. }
  167. };
  168.  
  169. /**
  170. * Wrapper for a 'button' html element.
  171. * @param {string} [className] - the value for the <code>class</code> attribute
  172. * @param {function} [callback] - the callback function for the <code>onclick<code> event
  173. * @param {string} [text] - the content text of the element (text shown on the button)
  174. * @param {string} [id] - the value for the <code>id</code> attribute
  175. * @constructor
  176. */
  177. function Button(className, callback, text, id) {
  178. if (!(this instanceof Button)) {
  179. return new Button(className, callback, text, id);
  180. }
  181. Element.call(this, 'BUTTON', id, className);
  182. if (typeof callback === 'function') {
  183. this.domElement.addEventListener('click', callback);
  184. }
  185. if (typeof text !== 'undefined') {
  186. this.domElement.appendChild(document.createTextNode(text));
  187. }
  188. }
  189. objectUtils.extend(Button).from(Element);
  190.  
  191. /**
  192. * Wrapper for a 'div' html element.
  193. * @param {string} [id] - The value for the <code>id</code> attribute
  194. * @param {string} [className] - The value for the <code>class</code> attribute
  195. * @constructor
  196. */
  197. function Div(id, className) {
  198. if (!(this instanceof Div)) {
  199. return new Div(className, id);
  200. }
  201. Element.call(this, 'DIV', id, className);
  202. }
  203. objectUtils.extend(Div).from(Element);
  204.  
  205. /**
  206. * Wrapper for an 'input' HTML element as a field for text.
  207. * @param {number|string} [maxLength] - The maximum number of characters
  208. * @param {string} [text] - The value of the <code>text</code> attribute (content initially shown in the field)
  209. * @param {string} [className] - The value for the <code>class</code> attribute
  210. * @param {string} [id] - The value for the <code>id</code> attribute
  211. * @constructor
  212. */
  213. function Input(maxLength, text, className, id) {
  214. if (!(this instanceof Input)) {
  215. return new Input(maxLength, text, className, id);
  216. }
  217. Element.call(this, 'INPUT', id, className);
  218. if (typeof maxLength !== 'undefined') {
  219. this.domElement.maxlength = maxLength;
  220. }
  221. if (typeof text !== 'undefined') {
  222. this.domElement.value = text;
  223. }
  224. }
  225. objectUtils.extend(Input).from(Element);
  226.  
  227. /**
  228. * Creates an 'input' HTML element of type 'checkbox'.
  229. * @param {function} [callback] - The callback function for the <code>onChange<code> event
  230. * @param {string} [className] - The value for the <code>class</code> attribute
  231. * @param {string} [id] - The value for the <code>id</code> attribute
  232. * @constructor
  233. */
  234. function Checkbox (callback, className, id) {
  235. if (!(this instanceof Checkbox)) {
  236. return new Checkbox(callback, className, id);
  237. }
  238. Element.call(this, 'INPUT', id, className);
  239. this.domElement.type = 'checkbox';
  240. if (typeof callback === 'function') {
  241. this.domElement.addEventListener('change', callback);
  242. }
  243. }
  244. objectUtils.extend(Checkbox).from(Element);
  245.  
  246. /**
  247. * Wrapper for a 'label' html element.
  248. * @param {string} htmlFor - The value of the <code>for</code> attribute. The id value of another element to bind the label to that element.
  249. * @param {string} [text] - The content text of the element (text shown on the label)
  250. * @param {string} [className] - The value for the <code>class</code> attribute
  251. * @param {string} [id] - The value for the <code>id</code> attribute
  252. * @constructor
  253. */
  254. function Label(htmlFor, text, className, id) {
  255. if (!(this instanceof Label)) {
  256. return new Label(htmlFor, text, className, id);
  257. }
  258. Element.call(this, 'LABEL', id, className);
  259. if (typeof text !== 'undefined') {
  260. this.domElement.appendChild(document.createTextNode(text));
  261. }
  262. if (typeof htmlFor !== 'undefined') {
  263. this.domElement.htmlFor = htmlFor;
  264. }
  265. }
  266. objectUtils.extend(Label).from(Element);
  267.  
  268. /**
  269. * Wrapper for a 'TextArea' html element.
  270. * @param {number|string} [cols] - The number of columns
  271. * @param {number|string} [maxLength] The maximum number of characters
  272. * @param {string} [text] - The value of the <code>text</code> attribute (content initially shown in the field)
  273. * @param {string} [className] - The value for the <code>class</code> attribute
  274. * @param {string} [id] - The value of the <code>id</code> attribute
  275. * @constructor
  276. */
  277. function TextArea(cols, maxLength, text, className, id) {
  278. if (!(this instanceof TextArea)) {
  279. return new TextArea(cols, maxLength, text, className, id);
  280. }
  281. Element.call(this, 'TEXTAREA', id, className);
  282. if (typeof cols !== 'undefined') {
  283. this.domElement.cols = cols;
  284. }
  285. if (typeof maxLength !== 'undefined') {
  286. this.domElement.maxlength = maxLength;
  287. }
  288. if (typeof text !== 'undefined') {
  289. this.domElement.value = text;
  290. }
  291. }
  292. objectUtils.extend(TextArea).from(Element);
  293.  
  294. /**
  295. * Wrapper for an 'option' html element which can be added to a 'select' html element.
  296. * @param text The value of the <code>text</code> attribute shown in the select dropdown
  297. * @param value THe value of the <code>value</code> attribute
  298. * @constructor
  299. */
  300. function Option(text, value) {
  301. if (!(this instanceof Option)) {
  302. return new Option(text, value);
  303. }
  304. Element.call(this, 'OPTION');
  305. this.domElement.text = text;
  306. this.domElement.value = value;
  307. }
  308. objectUtils.extend(Option).from(Element);
  309.  
  310. /**
  311. * Wrapper for a 'Select' html element.
  312. * @param {string} [id] - The value of the <code>id</code> attribute
  313. * @param {function} [callback] - callback function triggered by the events <code>OnChange</code>, <code>OnKeyUp</code> and <code>OnFocus</code>
  314. * @param {string} [className] - The value for the <code>class</code> attribute
  315. * @constructor
  316. */
  317. function Select(className, callback, id) {
  318. if (!(this instanceof Select)) {
  319. return new Select(className, id);
  320. }
  321. Element.call(this, 'SELECT', id, className);
  322.  
  323. var idx = keeper.push({ onChangeCallback : callback });
  324. Object.defineProperty(this, 'idx', { get: function() { return idx } });
  325. Select.prototype.setOnChangeKeyUpFocus(callback);
  326. }
  327. Select.prototype = {
  328. constructor: Select,
  329. addNewOption: function(text, value) {
  330. var newOption = Option(text, value);
  331. this.domElement.add(newOption.domElement);
  332. return newOption;
  333. },
  334. sortOptionsByText: function(isOrderDesc) {
  335. sortSelectBy(this.domElement, 'text', isOrderDesc);
  336. },
  337. sortOptionsByValue: function(isOrderDesc) {
  338. sortSelectBy(this.domElement, 'value', isOrderDesc);
  339. },
  340. /**
  341. * Sets a callback function triggered from the events <code>OnChange</code>, <code>OnKeyUp</code> and <code>OnFocus</code>.
  342. * Removes any former callback function registered to these events.
  343. * @param {function} callback
  344. */
  345. setOnChangeKeyUpFocus: function(callback) {
  346. var newCallback = (typeof callback === 'function') ? callback : objectUtils.emptyFunction;
  347.  
  348. var formerCallback = keeper.get(this.idx).onChangeCallback;
  349. this.domElement.removeEventListener("focus", formerCallback);
  350. this.domElement.removeEventListener("change", formerCallback);
  351. this.domElement.removeEventListener("keyup", formerCallback);
  352.  
  353. keeper.get(this.idx).onChangeCallback = newCallback;
  354. this.domElement.addEventListener("focus", newCallback);
  355. this.domElement.addEventListener("change", newCallback);
  356. this.domElement.addEventListener("keyup", newCallback);
  357. }
  358. };
  359. objectUtils.extend(Select).from(Element);
  360.  
  361. /**
  362. * Parses a param object into a query string and vice verca.
  363. * @param {Object|string} query - the queryObject object or query string
  364. * @return {string|Object}
  365. */
  366. var parseParams = function(query){
  367. if (typeof query === 'string') {
  368. var result = {};
  369. var decode = function(s) {
  370. return decodeURIComponent(s.replace(/\+/g, " "));
  371. };
  372. var match, search = /([^&=]+)=?([^&]*)/g;
  373. while ((match = search.exec(query)) !== null) {
  374. result[decode(match[1])] = decode(match[2]);
  375. }
  376. return result;
  377. } else {
  378. var result = "";
  379. Object.keys(query).forEach(function(key, index) {
  380. if (index >= 1) {
  381. result += "&";
  382. }
  383. result += key + "=" + query[key];
  384. });
  385. return result;
  386. }
  387. };
  388.  
  389. /**
  390. * Deals with parameters of a query.
  391. * @param {string|Object} query - the query search as a string or as parameter object in {key:value} form
  392. * @constructor
  393. */
  394. function Params(query) {
  395. if (!(this instanceof Params)) {
  396. return new Params(query);
  397. }
  398. var _params = {};
  399. Object.defineProperties(this, {
  400. /** The {key:value} parameter object */
  401. queryObject: {
  402. get: function() { return _params; },
  403. enumerable: true, configurable: true
  404. },
  405. /** The queryString without leading '?' */
  406. queryString: {
  407. get: function () {
  408. if (!_params || Object.keys(_params).length === 0) {
  409. return "";
  410. } else {
  411. return parseParams(_params);
  412. }
  413. },
  414. set: function(val) {
  415. if (val) {
  416. if (val.charAt(0) === '?') {
  417. val = val.substring(1);
  418. }
  419. _params = parseParams(val);
  420. } else {
  421. _params = {};
  422. }
  423. },
  424. enumerable: true, configurable: true
  425. }
  426. });
  427. if (typeof query === 'string') {
  428. this.queryString = query;
  429. } else {
  430. _params = query;
  431. }
  432. Object.defineProperty(this, "value", {
  433. get: function () { return this.queryString; }
  434. });
  435. }
  436. objectUtils.extend(Params).from(objectUtils.Truthy);
  437.  
  438. var getPageAsync = function(url, onSuccess, onError) {
  439. if (typeof onSuccess !== 'function') { onSuccess = objectUtils.emptyFunction;}
  440. if (typeof onError !== 'function') { onError = objectUtils.emptyFunction;}
  441.  
  442. return GM_xmlhttpRequest({
  443. method: 'GET',
  444. url: url,
  445. onload: function(resp) {
  446. if (resp.status == 200 || resp.status == 304) {
  447. resp.html = new DOMParser().parseFromString(resp.responseText, 'text/html');
  448. onSuccess(resp);
  449. } else {
  450. onError(resp);
  451. }
  452. },
  453. onerror: onError
  454. });
  455. };
  456.  
  457. return {
  458. Element: Element,
  459. Button: Button,
  460. Div : Div,
  461. Input : Input,
  462. Checkbox : Checkbox,
  463. Label : Label,
  464. TextArea : TextArea,
  465. Option : Option,
  466. Select : Select,
  467. Params : Params,
  468. requestPageAsync : getPageAsync
  469. };
  470. })();

QingJ © 2025

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