UNPKG

2.22 kBJavaScriptView Raw
1/*
2Copyright 2013-2015 ASIAL CORPORATION
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15
16*/
17
18import util from '../ons/util.js';
19
20/**
21 * Add vendor prefix.
22 *
23 * @param {String} name
24 * @return {String}
25 */
26const prefix = (function() {
27 const styles = window.getComputedStyle(document.documentElement, '');
28 const prefix = (Array.prototype.slice
29 .call(styles)
30 .join('')
31 .match(/-(moz|webkit|ms)-/) || (styles.OLink === '' && ['', 'o'])
32 )[1];
33
34 return function(name) {
35 return '-' + prefix + '-' + util.hyphenate(name);
36 };
37})();
38
39
40/**
41 * Minimal utility library for manipulating element's style.
42 * Set element's style.
43 *
44 * @param {Element} element
45 * @param {Object} styles
46 * @return {Element}
47 */
48const styler = function(element, style) {
49 Object.keys(style).forEach(function(key) {
50 if (key in element.style) {
51 element.style[key] = style[key];
52 } else if (prefix(key) in element.style) {
53 element.style[prefix(key)] = style[key];
54 } else {
55 util.warn('No such style property: ' + key);
56 }
57 });
58 return element;
59};
60
61/**
62 * @param {Element} element
63 * @param {String} styles Space-separated CSS properties to remove
64 */
65styler.clear = function(element, styles = '') {
66 const clearlist = styles.split(/\s+/).reduce((r, s) => r.concat([util.hyphenate(s), prefix(s)]), []),
67 keys = [];
68
69 for (let i = element.style.length - 1; i >= 0; i--) {
70 const key = element.style[i];
71 if (clearlist.length === 0 || clearlist.some(s => key.indexOf(s) === 0)) {
72 keys.push(key); // Store the key to fix Safari style indexes
73 }
74 }
75
76 keys.forEach(key => element.style[key] = '');
77 element.getAttribute('style') === '' && element.removeAttribute('style');
78};
79
80export default styler;