问题描述
我在功能中使用CSS变量,用户可以选择将字体大小更改为小,中或大。因此,对于大多数领域,它都按预期工作。但是对于某些字段,该值适用但未反映
:host-context(.mediumFont) {
--fontSize: 11px;
}
:host-context(.largeFont) {
--fontSize: 12px;
}
:host-context(.smallFont) {
--fontSize: 10px;
}
refClassArray: RefClassInterface[] = [
{ class: 'font-small',refClass: 'smallFont' },{ class: 'font-medium',refClass: 'mediumFont' },{ class: 'font-large',refClass: 'largeFont' },];
defaultFontSize = 'mediumFont';
changeFontSize(selector: string) {
this.defaultFontSize = selector;
let docBody = document.body;
console.log(document.getElementById(selector));
docBody.classList.add(selector);
this.refClassArray.forEach((refClass: RefClassInterface) => {
if (selector !== refClass.refClass) {
docBody.classList.remove(refClass.refClass);
document.querySelector('#' + refClass.refClass).setAttribute('style','font-weight: normal;' + 'pointer-events: auto;');
} else {
document.querySelector('#' + refClass.refClass).setAttribute('style','font-weight:' + 'bold;' + 'pointer-events: none;');
}
});
this.ieStyles.iEfont(selector);
}
以上是我使用的逻辑。
第一个图片来自运行良好的元素。当我将鼠标悬停在--font-size
上时,就会反映出11px
。第二个是它没有按预期运行的状态,当我将鼠标悬停在--font-size
上时,什么都没有出现。这两个元素都在<body>
解决方法
您不应通过直接访问来修改html代码。这样可能会使您的应用程序容易受到XSS攻击。
相反,Angular团队推荐使用Renderer2。
接受代码并对其进行修改以使用它,将导致以下情况:
refClassArray: RefClassInterface[] = [
{ class: 'font-small',refClass: 'smallFont' },{ class: 'font-medium',refClass: 'mediumFont' },{ class: 'font-large',refClass: 'largeFont' },];
defaultFontSize = 'mediumFont';
changeFontSize(selector: string,indexOfClassToAdd: number) {
this.defaultFontSize = selector;
const el: Element = document.getElementById(selector));
// Iterate each class in the list to remove it.
this.refClassArray.forEach((refClass: RefClassInterface) => {
// Remove the class from the specific element only if its present.
if (el.classList.contains(refClass.refClass) {
this.renderer2.removeClass(el,refClass.refClass);
};
});
this.renderer2.addClass(el,refClassArray[indexOfClassToAdd].refClass);
};
这意味着您知道要应用的class
(并且它存在于style.scss
或相应的scss文件中)。
亲切的问候。
,出于好奇,为什么要这样做而不是简单地使用具有所需文本大小的类?
无论哪种方式,似乎都没有应用您的值,因为您的选择器不够具体。
要对此进行更正,您可以使用类似以下内容的人工特定选择器:
html > body * { // rules }
为什么不使用ngClass
?
定义三个类
.font-small{
fontSize: 10px
}
.font-medium{
fontSize: 11px
}
.font-large{
fontSize: 12px
}
绑定用户选择的内容,例如userChoice: SizeEnum
或其他内容
然后,在您的数据元素上,使用ngClass进行绑定
ngClass = "{
'font-small': userChoice === sizeEnum.small,'font-medium': userChoice === sizeEnum.medium,'font-large': userChoice === sizeEnum.large
}"
,
通过移动解决了问题
:host-context(.mediumFont) {
--fontSize: 11px;
}
:host-context(.largeFont) {
--fontSize: 12px;
}
:host-context(.smallFont) {
--fontSize: 10px;
}
从app.component.scss
到styles.scss
。由于弹出式窗口不是app.compontnet.html
的一部分,因此它们会在弹出窗口之外呈现。