innertext.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /**
  2. * @fileOverview
  3. *
  4. * innerText polyfill
  5. *
  6. * @author: techird
  7. * @copyright: Baidu FEX, 2014
  8. */
  9. define(function(require, exports, module) {
  10. if ((!('innerText' in document.createElement('a'))) && ('getSelection' in window)) {
  11. HTMLElement.prototype.__defineGetter__('innerText', function() {
  12. var selection = window.getSelection(),
  13. ranges = [],
  14. str, i;
  15. // Save existing selections.
  16. for (i = 0; i < selection.rangeCount; i++) {
  17. ranges[i] = selection.getRangeAt(i);
  18. }
  19. // Deselect everything.
  20. selection.removeAllRanges();
  21. // Select `el` and all child nodes.
  22. // 'this' is the element .innerText got called on
  23. selection.selectAllChildren(this);
  24. // Get the string representation of the selected nodes.
  25. str = selection.toString();
  26. // Deselect everything. Again.
  27. selection.removeAllRanges();
  28. // Restore all formerly existing selections.
  29. for (i = 0; i < ranges.length; i++) {
  30. selection.addRange(ranges[i]);
  31. }
  32. // Oh look, this is what we wanted.
  33. // String representation of the element, close to as rendered.
  34. return str;
  35. });
  36. HTMLElement.prototype.__defineSetter__('innerText', function(text) {
  37. /**
  38. * @Desc: 解决FireFox节点内容删除后text为null,出现报错的问题
  39. * @Editor: Naixor
  40. * @Date: 2015.9.16
  41. */
  42. this.innerHTML = (text || '').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
  43. });
  44. }
  45. });