gpt4 book ai didi

javascript - 如何使用 Polymer 修改自定义全局样式的值?

转载 作者:行者123 更新时间:2023-11-29 23:54:05 25 4
gpt4 key购买 nike

例如,如果我写:

<style is="custom-style">
:root {
--p-color: red;
}
</style>

它将定义一个变量,我可以在我的范围内使用它:

<dom-module id="so-example">
<template>
<style>
:host p {
color: var(--p-color);
}
</style>

<p>this is a test</p>
</template>
<script>Polymer({ is: 'so-example' });</script>
</dom-module>
...
<so-example></so-example>

现在,假设我只想在 so-example 的范围内更改样式。我可以写:

var el = document.querySelector('so-example');
el.customStyle['--p-color'] = 'red';
el.updateStyles();

这将神奇地改变范围内所有段落的颜色。但我使用 is="custom-style" block 的原因是因为 --p-color 用于各种不同的元素。而现在我不能用上面的方法来改变它的值。如果我这样做,它只会像我说的那样改变示波器的颜色。

有没有办法在文档范围内定义这个变量时修改它?

最佳答案

您可以使用 Polymer.updateStyles({/* new styles */}) 全局更新样式,而不是在每个元素上调用 updateStyles()

Polymer.updateStyles({
'--p-color': 'blue'
});

HTMLImports.whenReady(() => {
Polymer({
is: 'x-foo'
});
Polymer({
is: 'x-bar'
});
});

function changeColor() {
Polymer.updateStyles({
'--p-color': 'blue'
});
}
<head>
<base href="https://polygit.org/polymer+1.8.0/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="polymer/polymer.html">
</head>
<body>
<style is="custom-style">
:root {
--p-color: red;
}
</style>
<x-foo></x-foo>
<x-bar></x-bar>
<button onclick="changeColor()">Change color</button>

<dom-module id="x-foo">
<template>
<style>
p {
color: var(--p-color);
}
</style>
<p>x-foo</p>
</template>
</dom-module>

<dom-module id="x-bar">
<template>
<style>
p {
color: var(--p-color);
}
</style>
<p>x-bar</p>
</template>
</dom-module>
</body>

关于javascript - 如何使用 Polymer 修改自定义全局样式的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42113540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com