无法使用带有Polymer 1.x或2.x的Shadow DOM设置元素的样式。考虑Polymer 2.0中的以下自定义元素:
<link rel="import" href="../polymer/polymer.html">
<!--
`semantic-ui-button`
@demo demo/index.html
-->
<dom-module id="polymer-button">
<template>
<div class$="button {{size}}">{{label}}</div>
</template>
<script>
class MyElement extends Polymer.Element {
static get is() {
return 'polymer-button';
}
static get properties() {
return {
label: {
type: String,
value: 'polymer-element'
},
size: { type: String }
};
}
}
window.customElements.define(MyElement.is, MyElement);
</script>
</dom-module>
在演示中:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes">
<title>polymer-element demo</title>
<script src="../../webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="../../iron-demo-helpers/demo-pages-shared-styles.html">
<link rel="import" href="../../iron-demo-helpers/demo-snippet.html">
<link rel="import" href="../polymer-element.html">
<style is="custom-style" include="demo-pages-shared-styles"></style>
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
.button {
background: #ccc;
border-radius: 4px;
color: #444;
}
.button.big {
font-size: 1rem;
padding: 6px;
}
</style>
</head>
<body>
<div class="vertical-section-container centered">
<h3>Basic polymer-element demo</h3>
<demo-snippet>
<template>
<polymer-button label="Demo"></polymer-button>
</template>
</demo-snippet>
</div>
</body>
</html>
.button
和.button.big
演示中定义的样式不应用于阴影元素;但是,在Polymer 1.x中,样式应用如果我们使用ShadyDOM:
<link rel="import" href="../polymer/polymer.html">
<!--
`polymer-button`
@demo demo/index.html
-->
<dom-module id="polymer-button">
<template>
<div class$="button {{size}}">{{label}}</div>
</template>
<script>
Polymer({
is: 'polymer-button',
properties: {
label: { type: String }
},
});
</script>
</dom-module>
有没有办法使用external styles选择/设置这些内部元素?
下面是我按照外观顺序展示的内容:
答案 0 :(得分:6)
启用样式点use CSS variables/mixins。
在元素的模板中添加<style>
标记:
<dom-module id="polymer-button">
<template>
<style>
.button {
@apply --my-button-mixin;
}
.button.big {
@apply --my-button-big-mixin;
}
</style>
...
</template>
</dom-module>
在容器元素中指定mixin:
<dom-module id="x-foo">
<template>
<style>
polymer-button {
--my-button-mixin: {
background: red;
color: white;
};
}
</style>
<polymer-button label="Red button"></polymer-button>
</template>
</dom-module>
...或index.html
:
<body>
<custom-style>
<style>
polymer-button {
--my-button-mixin: {
background: red;
color: white;
};
}
</style>
</custom-style>
<polymer-button label="Red button"></polymer-button>
</body>
答案 1 :(得分:5)
或者,您可以在自定义元素<style>
中添加一个带有@import url
规则的<template>
元素,该元素将导入外部样式表:
<template>
<style>
@import url( external.css )
</style>
<div class$="button {{size}}">{{label}}</div>
</template>
在CSS样式表(例如: external.css )中,您可以定义标准CSS:
.button {
background: #ccc;
border-radius: 4px;
color: #444;
}
.button.big {
font-size: 1rem;
padding: 6px;
}