【js】操作css、class、在head中增加css样式表

修改class

var usericon = document.querySelector("#username").parentNode
// 第一种方式:.className
usericon.className = "userContent"
// 第er 种方式:.setAttribute("class","xx")
usericon.setAttribute("class", "eye iconfontHide icon-yanjing_yincang_o")

修改css样式

div.setAttribute("style", "width: 26px; height: 26px; line-height: 30px;")

在head中增加css样式表

function addCssByStyle(cssString) {
   var style = document.createElement("style");
   style.setAttribute("type", "text/css");

   if (style.styleSheet) {// IE
      style.styleSheet.cssText = cssString;
   } else {// w3c
      var cssText = document.createTextNode(cssString);
      style.appendChild(cssText);
   }

   var heads = document.getElementsByTagName("head");
   if (heads.length) {
      heads[0].appendChild(style);
   } else {
      document.documentElement.appendChild(style);
   }
}
//添加css
addCssByStyle(".bodyimg{display:none;}.bodyback{background:url(platform/runtime/sys/web/assets/img/background.jpg) no-repeat !important;}.login-setting-whole{display:none;}.login-setting-out{width:1240px;height:534px;left:50%;top:50%;transform:translate(-50%,-50%);position:relative;background:url(platform/runtime/sys/web/assets/img/body-img.png) no-repeat;background-size:650px;background-position:0 150px;}.login-setting-sectionex-right{top:0 !important;margin-top:0 !important;right:0;}")

在head中就会出现对应的样式
在这里插入图片描述

生成css

   utils.setStyle = function (cssText, id) {
        var head = document.getElementsByTagName('head')[0] || document.documentElement;
        var element = document.getElementById(id);
        $(element).remove();

        element = document.createElement('style');
        id && (element.id = id);
        element.type = "text/css";
        head.appendChild(element);
        if (element.styleSheet !== undefined) {
            // IE http://support.microsoft.com/kb/262161
            if (document.getElementsByTagName('style').length > 31) {
                throw new Error('Exceed the maximal count of style tags in IE')
            }
            element.styleSheet.cssText = cssText
        } else {
            element.appendChild(document.createTextNode(cssText));
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值