简体   繁体   English

动态更改无html元素的样式

[英]change style dynamically of none html element

I'm using angularJs and want to change the style of an attribute dynamically. 我正在使用angularJs,并希望动态更改属性的样式。 Normally I would do this with ng-style in the html element. 通常,我会使用html元素中的ng-style进行此操作。

But I want to apply styles to the track of a range input. 但是我想将样式应用于范围输入的轨迹。 This element can be accessed in css like that: .slider::-webkit-slider-runnable-track (As Example for the webkit selector). 可以使用如下方式在CSS中访问此元素: .slider::-webkit-slider-runnable-track (以webkit选择器为例)。 Can I change the style for such an attribute in a function where I have the id for this element? 我可以在具有该元素ID的函数中更改此类属性的样式吗?

Eg (how I would do it in jquery): 例如(我将如何在jquery中做到):

$scope.change = function(id, value) {
        $('#'+id+'::-webkit-slider-runnable-track').css('background-image',value);
};

Javascript generally don't have access to pseudo elements, one possible workaround would be to insert a style tag Javascript通常无法访问伪元素,一种可能的解决方法是插入样式标签

$scope.change = function(id, value) {
    var style  = document.createElement('style');
    var styles = '{ background: red }';

    style.innerHTML = '#' + id + '::-webkit-slider-runnable-track ' + styles;
    document.head.appendChild(style)
};

FIDDLE 小提琴

Another way would be to keep the styles in the stylesheet, and just use a different class for a different style 另一种方法是将样式保留在样式表中,仅对不同的样式使用不同的类

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

and then do 然后做

document.getElementById('test').classList.add('red');

FIDDLE 小提琴

for AngularJs I recommend not to use $scope but use service, factory or directory instead for CSS type of work on html template. 对于AngularJ,我建议不要使用$ scope,而应使用service,factory或directory代替html模板上的CSS类型的工作。

however if you must still want to take this approach you can: 但是,如果您仍然必须采用这种方法,则可以:

$scope.change = function(id, cssClass, add) {
    var el = angular.element(document.querySelector(id));

    if (add) {
       el.addClass(cssClass);
    } else {
       el.removeClass(cssClass);
    }
}

where you can pass id for element, cssClass from your css class and use add as bool value; 您可以在其中从CSS类传递元素cssClass id ,并使用add作为bool值; pass what ever you want. 通过你想要的一切。

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

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