简体   繁体   English

在 angular2 中以编程方式设置 html slider 背景

[英]Set the html slider background programmatically in angular2

I want to create a custom slider component, where the background color should be set with angular data binding.我想创建一个自定义 slider 组件,其中背景颜色应使用 angular 数据绑定设置。

Here is a simple stackblitz example where the default color green should be overridden/exchanged with the data-bound color red.这是一个简单的stackblitz 示例,其中默认颜色绿色应该被数据绑定颜色红色覆盖/交换。

What I tried:我尝试了什么:

  • I know that sliders aren't standardized and that every browser has it's own representation我知道滑块不是标准化的,每个浏览器都有自己的表示
  • I can't create many css classes with ng-deep like in this question because the background color should be data-bound.我不能像这个问题一样使用 ng-deep 创建许多 css 类,因为背景颜色应该是数据绑定的。
  • I tried with ngAfterViewInit() and document.getElementByID('slider'), but I can't get the access to the inner browser specific items (like webkit-slider-runnable-track)我尝试使用 ngAfterViewInit() 和 document.getElementByID('slider'),但无法访问内部浏览器特定项目(如 webkit-slider-runnable-track)

Question问题

  • Is there an "angular way" to create a property binding to background color of a slider?是否有“角度方式”来创建与 slider 的背景颜色绑定的属性?
  • If not.如果不。 Is there any way to set the background color of a slider within angular (with Javascript?)有什么方法可以在 angular 中设置 slider 的背景颜色(使用 Javascript?)

You can use the power of css variables.您可以使用 css 变量的强大功能。

CSS CSS

.slider{
  --bg: green;
}

::-webkit-slider-runnable-track {
  background:var(--bg);
}

::-ms-track {
  background: var(--bg);
}

::-moz-range-track {
  background: var(--bg);
}

HTML: HTML:

Set {{color}} as background for this slider:
<br />
<div class="slider" [attr.style]="sanitizer.bypassSecurityTrustStyle('--bg:' + color)">
    <input id='slider' type="range">
</div>

Here is the implementation: https://stackblitz.com/edit/angular-oygzgp这是实现: https://stackblitz.com/edit/angular-oygzgp

You can use ngClass to set your color dynamically您可以使用 ngClass 动态设置颜色

in your css.在您的 css 中。

.test::-webkit-slider-runnable-track {
  background: red ;
}

.test::-ms-track {
  background:red ;
}

.test::-moz-range-track {
  background: red ;
}

in your html:在您的 html 中:

<input id='slider' type="range" [ngClass]="isRed ? 'red' : 'green'">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM