• javascript 一些关于css操作的函数


    // 通过样式表 获得css样式

    //obj 表示dom对象,name 表示css属性 比如width等
    function getStyle(obj,name){
    		if(obj.currentStyle){
    			return obj.currentStyle[name];
    		}else{
    			return getComputedStyle(obj,false)[name];
    		}
    }
    

     利用cssText 批量设置元素的属性

    obj.style.cssText="150px;height:500px;"

    和innerHTML一样,cssText很快捷且所有浏览器都支持。此外当批量操作样式时,cssText只需一次reflow,提高了页面渲染性能。

    但cssText也有个缺点,会覆盖之前的样式。

    但cssText也有个缺点,会覆盖之前的样式。如

    <div style="color:red;">TEST</div>
    
    div.style.cssText = "200px;";
    

    这时虽然width应用上了,但之前的color被覆盖丢失了。因此使用cssText时应该采用叠加的方式以保留原有的样式。

    function setStyle(el, strCss){
    	var sty = el.style;
    	sty.cssText = sty.cssText + strCss;
    }
    

    使用该方法在IE9/Firefox/Safari/Chrome/Opera中没什么问题,但由于 IE6/7/8中cssText返回值少了分号 会让你失望。

    因此对IE6/7/8还需单独处理下,如果cssText返回值没";"则补上

    function setStyle(el, strCss){
    	function endsWith(str, suffix) {
    		var l = str.length - suffix.length;
    		return l >= 0 && str.indexOf(suffix, l) == l;
    	}
    	var sty = el.style,
    		cssText = sty.cssText;
    	if(!endsWith(cssText, ';')){
    		cssText += ';';
    	}
    	sty.cssText = cssText + strCss;
    }
    

    通过class 获得元素

    //oParent 表示父元素  sclass 表示子元素的class名字
    function getByClass(oParent, sClass){ var aEle=oParent.getElementsByTagName('*'); var aResult=[]; for(var i=0;i<aEle.length;i++) { if(aEle[i].className==sClass) { aResult.push(aEle[i]); } } return aResult; }
  • 相关阅读:
    MySQL 慢日志没有自动创建新的日志文件
    Springboot为什么加载不上application.yml的配置文件
    android studio set proxy
    c++ win32 遍历进程列表
    React Prompt组件 阻止用户离开页面
    JS 浏览器上生成 UUID API
    部署 Nestjs 最佳实践
    Nginx 部署 单页面应用 + nodejs api 应用 最佳实践
    React JS: 如何使用 RxService 管理状态
    umijs 开发优化和生产优化
  • 原文地址:https://www.cnblogs.com/tl542475736/p/4025240.html
Copyright © 2020-2023  润新知