【问题标题】:Change auto generated CSS dynamically动态更改自动生成的 CSS
【发布时间】:2018-07-18 12:48:12
【问题描述】:

您能告诉我如何动态更改 css 吗?这里的问题是,css是由框架本身生成的。所以我不能声明或更改它。

这是在运行时:

我需要选择swiper-pagination-bullets 类并且需要有条件地给出底部值。像这样:

注意:这只是伪:

If="data!=null" {     
   .swiper-pagination-bullets {
            bottom: 190px !important;
        }
}
else{
  .swiper-pagination-bullets {
            bottom: 150px !important;
        }
}

【问题讨论】:

  • 你试过 !important 在@media 查询中吗?这可能会起作用并使其同时响应
  • 如何与媒体查询链接?我需要在移动设备上使用它。这里没有设备大小变化。有什么线索吗? @乔尼
  • 我不知道它只是移动的。但是,如果您以特定的分辨率声明更改,它可能会绕过并提供帮助。
  • 没有。这里没有分辨率或设备尺寸变化。我只需要根据条件不同地应用相同的类。我在上面的伪模式中显示了它。 @乔尼
  • 首先是类,不是css。二、你可以通过[class.foo]="true/false"添加/删除一个类

标签: javascript css angular sass ionic3


【解决方案1】:

与其动态更改 CSS,不如通过在运行时将样式表动态注入页面来覆盖它。

const style = document.createElement('style');
const bottom = condition ? 190 : 150;
style.insertRule(`.swiper-pagination-bullets { bottom: ${bottom}px; }`, 1);
document.head.appendChild(style);

我会尽量避免使用!important。如果您以上面显示的方式注入样式表,它已经优先于现有样式,因为它会出现在页面的后面,假设相同的选择器特异性。

或者你可以尝试通过.swiper-pagination-bullets.swiper-pagination-bullets 人为地增加特异性(在你认为合适的时候重复)。如果这不起作用,请使用!important

样式表注入代码取自here

【讨论】:

  • 非常感谢。我真的很喜欢用 Angular/Ionic 的方式来做。接受的答案就是这样做的。 +1 虽然:)
  • 不客气(:我不知道您想要一种 Angular/Ionic 方式,否则我不会建议它。也许您可以将这些关键字添加到标题或问题中,除了未来的标签(:
【解决方案2】:

就像在 cmets 中提到的@Duannx,您可以有条件地在ion-slides 元素中添加一个类,然后根据该类将 css 样式规则应用于分页器。

<ion-slides pager="true" [class.with-data]="data" ...>
    <ion-slide *ngFor="...">
        <!-- ... -->
    </ion-slide>
</ion-slides>

您需要更改 [class.with-data]="data" 并将其替换为组件中的真实属性,然后您可以在 SCSS 文件中使用它来更改分页器的样式:

ion-slides.with-data .swiper-pagination-bullets {     
    bottom: 190px !important;
}

ion-slides:not(.with-data) .swiper-pagination-bullets {
    bottom: 150px !important;
}

【讨论】:

  • 哦.. 这太棒了。非常感谢:)
  • 很高兴听到@Sampath :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-11
  • 2013-03-31
  • 2020-11-07
  • 2012-05-06
  • 2013-10-16
  • 1970-01-01
相关资源
最近更新 更多