• js和jquery设置css样式的几种方法


    一、js设置样式的方法

    1. 直接设置style的属性  某些情况用这个设置 !important值无效

    element.style.height = '50px';

    2. 直接设置属性(只能用于某些属性,相关样式会自动识别)

      element.setAttribute('height',50);

      element.setAttribute('height',50px');

    3. 设置style的属性

    element.setAttribute('style', 'height: 100px !important');

    4. 使用setProperty  如果要设置!important,推荐用这种方法设置第三个参数

    element.style.setProperty('height', '300px', 'important');

    5. 改变class   比如JQ的更改class相关方法

    因JS获取不到css的伪元素,所以可以通过改变伪元素父级的class来动态更改伪元素的样式

    element.className = 'blue';
    element.className += 'blue fb';

    6. 设置cssText

    element.style.cssText = 'height: 100px !important';
    element.style.cssText += 'height: 100px !important';


    二、jquery设置样式的几种方法

    1、设置所有匹配元素的指定 CSS 属性 不支持属性名称简写(如border和background)

    $(selector).css(name,value)

    2、使用函数来设置 CSS 属性
    $(selector).css(name,function(index,value))
    $("button").click(function(){
       $("p").css("color",function(){return "red";});
    });
    
    

     


    name:必需。规定 CSS 属性的名称。该参数可包含任何 CSS 属性,比如 "color";
    function(index,value):规定返回 CSS 属性新值的函数。index - 可选。接受选择器的 index 位置;value - 可选。接受 CSS 属性的当前值
    3、设置多个 CSS 属性/值对
    $(selector).css({property:value, property:value, ...})
    $("p").css({"color":"white","background-color":"#98bf21", "font-family":"Arial", "font-size":"20px","padding":"5px"});

     

    
    

     




     

  • 相关阅读:
    Android学习八---OpenCV JAVA API
    Android学习七---Hello OpenCV samples
    Android学习六---OpenCV for android samples
    android学习五---OpenCV for android环境搭建
    android学习四---Activity和Intent
    Servlet总结(Zpoor,你还说你不会Servlet?)
    Eclipse使用小技巧
    Java-List(冷静分析,稍加思索,识破)
    JDBC——setting useSSL=false, or set useSSL=true
    Java-foreach分析总结
  • 原文地址:https://www.cnblogs.com/nature-wind8/p/10423671.html
Copyright © 2020-2023  润新知