Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

266 řádky
7.9 KiB

  1. /*
  2. html5slider - a JS implementation of <input type=range> for Firefox 4 and up
  3. Copyright (c) 2010-2011 Frank Yan, <http://frankyan.com>
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. */
  20. (function() {
  21. // test for native support
  22. var test = document.createElement('input');
  23. try {
  24. test.type = 'range';
  25. if (test.type == 'range')
  26. return;
  27. } catch (e) {
  28. return;
  29. }
  30. // test for required property support
  31. if (!document.mozSetImageElement || !('MozAppearance' in test.style))
  32. return;
  33. var scale;
  34. var isMac = navigator.platform == 'MacIntel';
  35. var thumb = {
  36. radius: isMac ? 9 : 6,
  37. width: isMac ? 22 : 12,
  38. height: isMac ? 16 : 20
  39. };
  40. var track = '-moz-linear-gradient(top, transparent ' + (isMac ?
  41. '6px, #999 6px, #999 7px, #ccc 9px, #bbb 11px, #bbb 12px, transparent 12px' :
  42. '9px, #999 9px, #bbb 10px, #fff 11px, transparent 11px') +
  43. ', transparent)';
  44. var styles = {
  45. 'min-width': thumb.width + 'px',
  46. 'min-height': thumb.height + 'px',
  47. 'max-height': thumb.height + 'px',
  48. padding: 0,
  49. border: 0,
  50. 'border-radius': 0,
  51. cursor: 'default',
  52. 'text-indent': '-999999px' // -moz-user-select: none; breaks mouse capture
  53. };
  54. var onChange = document.createEvent('HTMLEvents');
  55. onChange.initEvent('change', true, false);
  56. if (document.readyState == 'loading')
  57. document.addEventListener('DOMContentLoaded', initialize, true);
  58. else
  59. initialize();
  60. function initialize() {
  61. // create initial sliders
  62. Array.forEach(document.querySelectorAll('input[type=range]'), transform);
  63. // create sliders on-the-fly
  64. document.addEventListener('DOMNodeInserted', onNodeInserted, true);
  65. }
  66. function onNodeInserted(e) {
  67. check(e.target);
  68. if (e.target.querySelectorAll)
  69. Array.forEach(e.target.querySelectorAll('input'), check);
  70. }
  71. function check(input, async) {
  72. if (input.localName != 'input' || input.type == 'range');
  73. else if (input.getAttribute('type') == 'range')
  74. transform(input);
  75. else if (!async)
  76. setTimeout(check, 0, input, true);
  77. }
  78. function transform(slider) {
  79. var isValueSet, areAttrsSet, isChanged, isClick, prevValue, rawValue, prevX;
  80. var min, max, step, range, value = slider.value;
  81. // lazily create shared slider affordance
  82. if (!scale) {
  83. scale = document.body.appendChild(document.createElement('hr'));
  84. style(scale, {
  85. '-moz-appearance': isMac ? 'scale-horizontal' : 'scalethumb-horizontal',
  86. display: 'block',
  87. visibility: 'visible',
  88. opacity: 1,
  89. position: 'fixed',
  90. top: '-999999px'
  91. });
  92. document.mozSetImageElement('__sliderthumb__', scale);
  93. }
  94. // reimplement value and type properties
  95. slider.__defineGetter__('value', function() {
  96. return '' + value;
  97. });
  98. slider.__defineSetter__('value', function(val) {
  99. value = '' + val;
  100. isValueSet = true;
  101. draw();
  102. });
  103. slider.__defineGetter__('type', function() {
  104. return 'range';
  105. });
  106. // sync properties with attributes
  107. ['min', 'max', 'step'].forEach(function(prop) {
  108. if (slider.hasAttribute(prop))
  109. areAttrsSet = true;
  110. slider.__defineGetter__(prop, function() {
  111. return this.hasAttribute(prop) ? this.getAttribute(prop) : '';
  112. });
  113. slider.__defineSetter__(prop, function(val) {
  114. val === null ? this.removeAttribute(prop) : this.setAttribute(prop, val);
  115. });
  116. });
  117. // initialize slider
  118. slider.readOnly = true;
  119. style(slider, styles);
  120. update();
  121. slider.addEventListener('DOMAttrModified', function(e) {
  122. // note that value attribute only sets initial value
  123. if (e.attrName == 'value' && !isValueSet) {
  124. value = e.newValue;
  125. draw();
  126. }
  127. else if (~['min', 'max', 'step'].indexOf(e.attrName)) {
  128. update();
  129. areAttrsSet = true;
  130. }
  131. }, true);
  132. slider.addEventListener('mousedown', onDragStart, true);
  133. slider.addEventListener('keydown', onKeyDown, true);
  134. slider.addEventListener('focus', onFocus, true);
  135. slider.addEventListener('blur', onBlur, true);
  136. function onDragStart(e) {
  137. isClick = true;
  138. setTimeout(function() { isClick = false; }, 0);
  139. if (e.button || !range)
  140. return;
  141. var width = parseFloat(getComputedStyle(this, 0).width);
  142. var multiplier = (width - thumb.width) / range;
  143. if (!multiplier)
  144. return;
  145. // distance between click and center of thumb
  146. var dev = e.clientX - this.getBoundingClientRect().left - thumb.width / 2 -
  147. (value - min) * multiplier;
  148. // if click was not on thumb, move thumb to click location
  149. if (Math.abs(dev) > thumb.radius) {
  150. isChanged = true;
  151. this.value -= -dev / multiplier;
  152. }
  153. rawValue = value;
  154. prevX = e.clientX;
  155. this.addEventListener('mousemove', onDrag, true);
  156. this.addEventListener('mouseup', onDragEnd, true);
  157. }
  158. function onDrag(e) {
  159. var width = parseFloat(getComputedStyle(this, 0).width);
  160. var multiplier = (width - thumb.width) / range;
  161. if (!multiplier)
  162. return;
  163. rawValue += (e.clientX - prevX) / multiplier;
  164. prevX = e.clientX;
  165. isChanged = true;
  166. this.value = rawValue;
  167. }
  168. function onDragEnd() {
  169. this.removeEventListener('mousemove', onDrag, true);
  170. this.removeEventListener('mouseup', onDragEnd, true);
  171. }
  172. function onKeyDown(e) {
  173. if (e.keyCode > 36 && e.keyCode < 41) { // 37-40: left, up, right, down
  174. onFocus.call(this);
  175. isChanged = true;
  176. this.value = value + (e.keyCode == 38 || e.keyCode == 39 ? step : -step);
  177. }
  178. }
  179. function onFocus() {
  180. if (!isClick)
  181. this.style.boxShadow = !isMac ? '0 0 0 2px #fb0' :
  182. '0 0 2px 1px -moz-mac-focusring, inset 0 0 1px -moz-mac-focusring';
  183. }
  184. function onBlur() {
  185. this.style.boxShadow = '';
  186. }
  187. // determines whether value is valid number in attribute form
  188. function isAttrNum(value) {
  189. return !isNaN(value) && +value == parseFloat(value);
  190. }
  191. // validates min, max, and step attributes and redraws
  192. function update() {
  193. min = isAttrNum(slider.min) ? +slider.min : 0;
  194. max = isAttrNum(slider.max) ? +slider.max : 100;
  195. if (max < min)
  196. max = min > 100 ? min : 100;
  197. step = isAttrNum(slider.step) && slider.step > 0 ? +slider.step : 1;
  198. range = max - min;
  199. draw(true);
  200. }
  201. // recalculates value property
  202. function calc() {
  203. if (!isValueSet && !areAttrsSet)
  204. value = slider.getAttribute('value');
  205. if (!isAttrNum(value))
  206. value = (min + max) / 2;;
  207. // snap to step intervals (WebKit sometimes does not - bug?)
  208. value = Math.round((value - min) / step) * step + min;
  209. if (value < min)
  210. value = min;
  211. else if (value > max)
  212. value = min + ~~(range / step) * step;
  213. }
  214. // renders slider using CSS background ;)
  215. function draw(attrsModified) {
  216. calc();
  217. if (isChanged && value != prevValue)
  218. slider.dispatchEvent(onChange);
  219. isChanged = false;
  220. if (!attrsModified && value == prevValue)
  221. return;
  222. prevValue = value;
  223. var position = range ? (value - min) / range * 100 : 0;
  224. var bg = '-moz-element(#__sliderthumb__) ' + position + '% no-repeat, ';
  225. style(slider, { background: bg + track });
  226. }
  227. }
  228. function style(element, styles) {
  229. for (var prop in styles)
  230. element.style.setProperty(prop, styles[prop], 'important');
  231. }
  232. })();