动态改变注入的CSS类...好吗? ...坏? [英] Dynamically Changing an Injected CSS Class ...Good? ...Bad?

查看:146
本文介绍了动态改变注入的CSS类...好吗? ...坏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

动态更改注入的CSS类...好吗? ... Bad?

我发现需要修改我注入到javascript标题的CSS类。因为我动态构建类并将它注入到头文件中,我发现很容易修改类的文本,并将其放回到CSS类定义中,从而改变它。

I found a 'need' to modify a CSS Class that I inject into the header vis javascript. Because I build the class dynamically and inject it into the header, I found it easy to modify the Class's text and put it back into the CSS Class definition whereby changing it.

通过inject,我的意思是:
var style = document.createElement('style');
style.type ='text / css';
style.innerHTML =.classname {... css text ...};
document.getElementsByTagName('head')[0] .appendChild(style);

By inject, I mean: var style = document.createElement('style'); style.type = 'text/css'; style.innerHTML = ".classname { ...css text... }"; document.getElementsByTagName('head')[0].appendChild(style);

并通过修改类,我的意思是简单地改变文本:
{ ... css text ...}

and by modifying the Class, I mean simply changing the text: { ...css text... }

并放回:
style.innerHTML =.classname {... new css text ...};

我真的没有看到这样做,我问,是否有一个原因,这是不是更经常? ...那是这是坏的做法吗?

I really have not seen this done before and am asking if there is a reason that this is not done more often? ...that is, "is this a bad practice?" and perhaps "are there browser/device combinations where this may not work?"

非常感谢。

推荐答案

这是一个坏的做法。一个CSS类应该有一个单一的定义。有条件地修改类会使您的代码难以跟踪,难以维护。

This is a bad practice. A CSS class should have a single definition. Modifying the class conditionally makes your code hard to follow and hard to maintain.

正确的方法是为每个条件创建一个单独的CSS类,或使用Javascript直接修改DOM。

The correct way would to be create a separate CSS class for each condition, or modify the DOM directly using Javascript.

这篇关于动态改变注入的CSS类...好吗? ...坏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆