简体   繁体   中英

change style dynamically of none html element

I'm using angularJs and want to change the style of an attribute dynamically. Normally I would do this with ng-style in the html element.

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). Can I change the style for such an attribute in a function where I have the id for this element?

Eg (how I would do it in 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

$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.

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; pass what ever you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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