Is there a way to reference an existing CSS style

2019-04-18 15:43发布

If I have a style defined

.style1
{
   width: 140px;
}

can I reference it from a second style?

.style2
{
   ref: .style1;
}

Or is there a way via javascript/jQuery?

--- Edit

To clarify the problem, I am trying to apply whatever style is defined for a #x and #c to .x and .c without altering the CSS as the CSS is going to have updates that are out of my control.

I used width but really the style would be something more complex with font, border and other style elements being specified.

Specifying multiple class names does work when the style is being applied to a class so I'll mark existing responses as answers, but I need to take the style being applied to an id and also apply it to a class style ... if that makes any sense.

7条回答
萌系小妹纸
2楼-- · 2019-04-18 16:38

Are you talking about getting all of the computed styles set on a particular Element and applying those to a second Element?

If that's the case, I think you're going to need to iterate through one Element's computed styles using and then apply those to your other Elements' cssText properties to set them as inline styles.

Something like:

el = document.getElementById('someId');
var cStyle = '';
for(var i in el.style){
  if(el.style[i].length > 0){ cStyle += i + ':' + el.style[i] + ';';
}
$('.someClass').each(function(){ this.style.cssText = cStyle; });

If you know that you'll only be dealing with a finite set of CSS properties, you could simplify the above as:

el = $('#someId');
var styleProps = {'border-top':true,'width':true,'height':true};
var cStyle = '';
for(var i in styleProps){
  cStyle += styleProps[i] + ':' + el.style(styleProps[i]) + ';';
}
$('.someClass').each(function(){ this.style.cssText = cStyle; });

I'll caveat the above code with the fact that I'm not sure whether or not the IEs will return a CSSStyleDeclaration Object for an HTMLElement's style property like Mozilla will (the first example). I also haven't given the above a test, so rely on it as pseudo-code only.

查看更多
登录 后发表回答