源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

JS函数实现动态添加CSS样式表文件

  • 时间:2022-07-28 20:09 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:JS函数实现动态添加CSS样式表文件
先给出函数。
[url=/stylesheets/print.css]<!--[ifltIE8]> <linkrel="stylesheet"href="/stylesheets/ie.css"type="text/css"media="screen"> <![endif]--> <%=javascript_tag"window._token='#{form_authenticity_token}'"ifActionController::Base.allow_forgery_protection%> <%=javascript_include_tag:defaults%> <styletype="text/css"media="print"></style> </head>
  上面用alert(document.styleSheets.length);测试一下,IE返回6,W3C游览器返回5。因此,否决了它。而且我们只用到style元素,不使用外联。第二部分的判定就针对head中的style元素而言,没有就创建一个。然后我们把CSS字符串加在第一个style元素就行了。   接着我们要加把保险锁,因为当media="print"时,只在页面打印时,定义的效果才有效。为了防止第一个style元素的media值不是screen,我们得改一改。   附上media的一些说明。   screen(缺省值),提交到计算机屏幕;   print,输出到打印机;   projection,提交到投影机;   aural,扬声器;   braille,提交到凸字触觉感知设备;   tty,电传打字机(使用固定的字体);   tv,电视机;   all,所有输出设备。   最后是如此添加的问题。分IE,火狐与其他游览器三种。判定游览器也用各自的私有属性或方法。如styleSheet是IE独用的,getBoxObjectFor是火狐独用的(当然你也可以使用(/firefox/.test(navigator.userAgent.toLowerCase())),通常DOM操作是最耗时的,能用私有就用私有!   使用方法。
[u]复制代码[/u] 代码如下:
addSheet(" .RTE_iframe{width:600px;height:300px;} .RTE_toolbar{width:600px;} .color_result{width:216px;} .color_view{width:110px;height:25px;} .color_code{text-align:center;font-weight:700;color:blue;font-size:16px;} div.table{width:176px;position:absolute;padding:1px;} div.tabletd{font-size:12px;color:red;text-align:center;} ");*/   对比一下51js的客服果果脚本,更短小,但是它会可能会创建多个style元素,还有一些效率的问题……毕竟我这个最初是为开发富文本编辑而开发的,功能不强大不行啊! /* 动态添加样式表的规则 */ iCSS={add:function(css){ varD=document,$=D.createElement('style'); $.setAttribute("type","text/css"); $.styleSheet&&($.styleSheet.cssText=css)|| $.appendChild(D.createTextNode(css)); D.getElementsByTagName('head')[0].appendChild($); }}; iCSS.add(" .dhoooListBox,.dhoooListBoxli{margin:0;padding:0;list-style-type:none;font-size:12px;cursor:default} .dhoooListBox{border:1pxsolid#aaa;width:180px;background:#eee;height:200px;overflow:auto;float:left} .dhoooListBoxli{margin:5px;line-height:24px;background:url(images/smilies/time.gif)no-repeat060%;padding-left:25px;color:#555;} .dhoooListBoxli.selected{background-color:#FFCC33} ");   最后追加几个相关的方法: vargetClass=function(ele){ returnele.className.replace(/s+/,'').split(''); }; varhasClass=function(ele,cls){ returnele.className.match(newRegExp('(\s|^)'+cls+'(\s|$)')); } varaddClass=function(ele,cls){ if(!this.hasClass(ele,cls))ele.className+=""+cls; } varremoveClass=function(ele,cls){ if(hasClass(ele,cls)){ varreg=newRegExp('(\s|^)'+cls+'(\s|$)'); ele.className=ele.className.replace(reg,''); } }
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部