【发布时间】:2016-08-29 17:50:55
【问题描述】:
我想使用 Javascript(动态)设置自定义 Polymer 元素的 :host{} 样式。我要设置样式的属性是“行高”,它会根据用户的屏幕大小而有所不同(文本总是在一行上)。
为了找到一个解决方案,我使用了两种不同的方法:
第一种是使用普通的 jquery:
<dom-module is="custom-element">
<template>
<style>
:host {
position: relative;
display: inline-block;
min-width: 5.15em;
min-height: 2em;
padding: 0.5em;
background: transparent;
font-size: 1.3em;
outline: none;
cursor: pointer;
color: #ABCFCA;
text-transform: uppercase;
text-align: center;
overflow: hidden;
}
</style>
<content></content>
</template>
<script>
Polymer({
is: "custom-element",
properties: {
},
ready: function() {
$(this).css("line-height", $(this).height() + "px");
}
});
</script>
我尝试的第二种方法是使用 Polymer 的自定义 css 属性:
<dom-module is="custom-element">
<template>
<style>
:host {
position: relative;
display: inline-block;
min-width: 5.15em;
min-height: 2em;
padding: 0.5em;
background: transparent;
font-size: 1.3em;
outline: none;
cursor: pointer;
color: #ABCFCA;
text-transform: uppercase;
text-align: center;
overflow: hidden;
line-height: --dynamic-line-height;
}
</style>
<content></content>
</template>
<script>
Polymer({
is: "custom-element",
properties: {
},
ready: function() {
this.customStyle['--dynamic-line-height'] = $(this).height();
this.updateStyles();
}
});
</script>
在第一种方法(纯 jquery)中,当使用 Chrome 的元素检查器检查元素时,line-height 属性甚至没有添加/设置,文本保持在默认的垂直位置
第二种方法最终与第一种方法相同(不改变/导致元素样式)
需要注意的是console.log($(this).height());产生32px的预期结果(在我的屏幕上)
如果有人可以帮助我修复/编辑我现有的任何方法,或者为我提供他们使用过/记录在某处的方法,那就太棒了。
谢谢。
【问题讨论】:
标签: javascript jquery polymer web-component shadow-dom