【发布时间】: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