Changing a CSS rule-set from Javascript

前端 未结 8 1051
甜味超标
甜味超标 2020-11-22 04:54

Is it possible to make changes to a CSS rule-set dynamically (i.e. some JS which would change a CSS rule-set when the user clicks a widget)

This particular CSS rule-

8条回答
  •  别那么骄傲
    2020-11-22 05:41

    While setAttribute is nice, there is a standard way of doing this across most browsers:

    htmlElement.className = 'someClass';
    

    To do it over many elements, you will need a cross browser solution:

    function getElementsByClassName( className, context, tagName ) {
      context = context || document;
      if ( typeof context.getElementsByClassName === 'function' )
        return context.getElementsByClassName( className );
    
      if ( typeof context.getElementsByTagName !== 'function' )
        return [];
    
      var elements = typeof tagName === 'string' ? context.getElementsByTagName( tagName ) :
        context.getElementsByTagName('*'),
      ret = [];
      for ( var i = 0, il = elements.length; i < il; i++ )
        if ( elements[ i ].className.match( className ) )
          ret.push( elements[ i ] );
    
      return ret;
    }
    
    var elements = getElementsByClassName('someClass');
    
    for ( var i = 0, il = elements.length; i < il; i++ )
      elements[ i ].className = 'newClass';
    

    You may want to replace the line:

    if ( elements[ i ].className.match( className ) )
    

    With some Regular Expression, but you will have to escape special characters in that case.

提交回复
热议问题