【问题标题】:is it possible to update variable value from html worker file?是否可以从 html 工作文件中更新变量值?
【发布时间】:2019-02-26 21:52:03
【问题描述】:

我正在学习如何将工作文件用于 html 页面。我正在尝试根据来自 worker.js 的返回值更新 css 变量。

如果我更新 worker.addEventListener 中的 css 变量,颜色会变为黄色。

如果我尝试更新 eventlistener 之外的 css 变量,它不会做任何事情,因为 mood_color 未定义。

是否可以从 html worker 为变量赋值?


HTML

    <style>
        :root {
            --mood-color: grey;
        }
    </style>

    <body>
        <h3 class="my_feelings" style="color: var(--mood-color)"> 
            My Feelings 
        <h3>
    </body>

jquery

​​>
    $(document).ready(function(){
        var worker = new Worker("/js/mood.js");
        var mood_color; 
        worker.addEventListener('message', function(e){
            mood_color = e.data;
            console.log(mood_color[0].color) // prints "yellow";

            // changes header color to yellow.
            $(".my_feelings").get(0).style.setProperty("--mood-color", mood_color); 

        });
        worker.postMessage("sunny");
        console.log(mood_color[0].color) // prints "undefined";

        // doesn't change mood color because mood_color is undefined
        $('.my_feelings').on('click', function(){
            $(".my_feelings").get(0).style.setProperty("--mood-color", mood_color); 

        });
    });

mood.js(html 工作者)

    var weather = [
        {"weather": "sunny", "mood": "happy", "color": "yellow"},
        {"weather": "rainy", "mood": "sad"}, "color": "blue"
    ];

    self.addEventListener('message', function(e) {
        var color = weather .filter(function(i, n){
            return i.weather == e.data;
        });
        self.postMessage(color);
    }, false);

【问题讨论】:

    标签: javascript jquery html worker css-variables


    【解决方案1】:

    您的代码存在许多问题。除了语法错误:

    mood_color 那时没有定义,因为postMessage 发送异步消息。因为它是异步的,所以响应要到稍后才会发生,在 console.log 运行之后。

    mood_color 最终被设置时,它被设置为一个对象数组(在这种情况下只有一个),而不是颜色,因为这是从工作人员传入的。具体来说,它设置为:

    [ { weather: 'sunny', mood: 'happy', color: 'yellow' } ]
    

    当您尝试将 CSS 变量设置为此时,数组被强制转换为字符串 "[object Object]" 并且 CSS 变量设置为该值。这就是为什么文本以黑色而不是您在 CSS 中设置的灰色或您尝试将其更改为的黄色结束的原因。 mood_color[0].color 会得到实际的颜色值。

    【讨论】:

    • 明白了!我忘记了 postMessage 发送了一条异步消息……这就是使用 worker 的全部意义所在。感谢您的澄清和样品!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多