dom_selection.html 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <!DOCTYPE html>
  2. <html>
  3. <!--
  4. Copyright 2010 The Closure Library Authors. All Rights Reserved.
  5. Use of this source code is governed by the Apache License, Version 2.0.
  6. See the COPYING file for details.
  7. -->
  8. <head>
  9. <title></title>
  10. <style>
  11. label {
  12. display: block;
  13. }
  14. </style>
  15. <script src="../base.js"></script>
  16. <script>
  17. goog.require('goog.dom');
  18. goog.require('goog.dom.selection');
  19. </script>
  20. </head>
  21. <body>
  22. <script>
  23. var $ = goog.dom.getElement;
  24. var isSyncing = false;
  25. function update(i) {
  26. isSyncing = true;
  27. var selectionStart = $('selectionStart' + i).value;
  28. var selectionEnd = $('selectionEnd' + i).value;
  29. var selectionText = $('selectionText' + i).value;
  30. var textField = $('textField' + i);
  31. textField.focus();
  32. if (!isNaN(selectionStart)) {
  33. goog.dom.selection.setStart(textField, selectionStart);
  34. }
  35. if (!isNaN(selectionEnd)) {
  36. goog.dom.selection.setEnd(textField, selectionEnd);
  37. }
  38. selection.setText(textField, selectionText);
  39. isSyncing = false;
  40. sync(i);
  41. }
  42. function sync(i) {
  43. isSyncing = true;
  44. var textField = $('textField' + i);
  45. $('selectionStart' + i).value = goog.dom.selection.getStart(textField);
  46. $('selectionEnd' + i).value = goog.dom.selection.getEnd(textField);
  47. $('selectionText' + i).value = goog.dom.selection.getText(textField);
  48. isSyncing = false;
  49. }
  50. </script>
  51. <label>selectionStart <input type=text id=selectionStart1></label>
  52. <label>selectionEnd <input type=text id=selectionEnd1></label>
  53. <label>selectionText <input type=text id=selectionText1></label>
  54. <button onclick="update(1)">Update Textarea</button><br>
  55. <textarea id=textField1 onkeydown="sync(1)" onkeyup="sync(1)"></textarea>
  56. <label>selectionStart <input type=text id=selectionStart2></label>
  57. <label>selectionEnd <input type=text id=selectionEnd2></label>
  58. <label>selectionText <input type=text id=selectionText2></label>
  59. <button onclick="update(2)">Update Input</button><br>
  60. <input type=text id=textField2 onkeydown="sync(2)" onkeyup="sync(2)">
  61. <script>
  62. window.onload = function() {
  63. sync(1);
  64. sync(2);
  65. };
  66. </script>
  67. </body>
  68. </html>