Firefox中未定义事件

时间:2017-10-31 13:29:50

标签: javascript firefox events

我想使用此代码更改主题颜色设置,但它不适用于Firefox。我使用的源代码来自这个网站:https://jonathan-harrell.com/experiment/live-theming-with-css-variables/。这是我的代码:

const setValue = (property, value) => {
    if (value) {
        document.documentElement.style.setProperty(`--${property}`, value);

        const input = document.querySelector(`#${property}`);
        if (input) {
            value = value.replace('px', '');
            input.value = value;
        }
    }
};

const setValueFromLocalStorage = property => {
    let value = localStorage.getItem(property);
    setValue(property, value);
};

const setTheme = options => {
    for (let option of Object.keys(options)) {
        const property = option;
        const value = options[option];

        setValue(property, value);
        localStorage.setItem(property, value);
    }
}

const dataThemeButtons = document.querySelectorAll('[data-theme]');

for (let i = 0; i < dataThemeButtons.length; i++) {
    dataThemeButtons[i].addEventListener('click', () => {
        const theme = dataThemeButtons[i].dataset.theme;
        switch (theme) {
            case 'default':
                setTheme({
                    'meta-menu-background-color': '#50463d',
                    'link-color': '#ed1347',
                    'header-menu-color': '#50463d',
                    'header-menu-background-color': '#ffffff',
                    'footer-background-color': '#3c332e',
                    'footer-last-background-color': '#50463d',
                });
            return;
        }
    })
}

document.addEventListener('DOMContentLoaded', () => {
    setValueFromLocalStorage('meta-menu-background-color'),
    setValueFromLocalStorage('link-color'),
    setValueFromLocalStorage('header-menu-color'),
    setValueFromLocalStorage('footer-background-color');
    setValueFromLocalStorage('footer-last-background-color');
});

const handleInputChange = (property, pixels) => {
    document.documentElement.style.setProperty(`--${property}`, `${event.target.value}${pixels ? 'px' : ''}`);
    localStorage.setItem(property, `${event.target.value}${pixels ? 'px' : ''}`);
};

document.querySelector('#meta-menu-background-color').addEventListener('change', event => {
    handleInputChange('meta-menu-background-color', false);
});

在Firefox控制台中,我在此行中看到错误“ReferenceError:event not defined”:

document.documentElement.style.setProperty(`--${property}`, `${event.target.value}${pixels ? 'px' : ''}`);

Chrome正常运行。

你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

IE和Chrome中的event符号是全局,但它在Firefox中作为参数传递。因此,您需要使用单个参数编写事件处理函数(如果需要,可以将其称为event),然后为每个处理程序添加一个前导码代码行:

function yourHandler(event) {
    event = event || window.event;
    // ...
}