• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • css()

    获取匹配元素集合中的第一个元素的样式属性的值或设置每个匹配元素的一个或多个CSS属性。

    .css(propertyName)
    • css(propertyName)
    • css(propertyNames)
    .css(propertyName, value)
    • css(propertyName, value)
    • css(propertyName, function(index, value))
    • css(properties)

    css(propertyName)

    获取匹配元素集合中的第一个元素的样式属性的值

    .css(propertyName)
    • propertyName类型: String。一个css属性名。

    .css()方法可以非常方便地获取匹配的元素集合中第一个元素的样式属性值,对于某些属性而言,浏览器访问样式属性的方式是不同的,该方法对于取得这些属性是非常方便的(例如,某些属性在标准浏览器下是通过的getComputedStyle()方法取得的,而在Internet Explorer下是通过currentStyleruntimeStyle属性取得的)并且,某些特定的属性,不同浏览器的写法不一。举个例子, Internet Explorer的DOM 将float属性写成styleFloat实现,W3C标准浏览器将float属性写成cssFloat。为了保持一致性,您可以简单地使用"float",jQuery将为每个浏览器返回它需要的正确值。

    另外,jQuery同样可以解析 CSS 和用multiple-word格式化(用横杠连接的词,比如:background-color)的DOM属性的不同写法。举个例子:jQery能解析.css('background-color').css('backgroundColor')并且返回正确的值。不同的浏览器可能会返回CSS颜色值在逻辑上相同,但在文字上表现不同,例如:#FFF,#ffffff,和 rgb(255,255,255)。

    简写速写的CSS属性(例如: margin, background, border)是不支持的,例如,如果你想重新获取margin,可以使用$(elem).css('marginTop')$(elem).css('marginRight'),其他的也是如此。

    从jQuery 1.9开始,传递一个CSS的样式属性的数组给.css()将返回属性-值配对的对象。例如,要获取元素4个边距宽度值border-width,你可以使用$(elem).css(["borderTopWidth","borderRightWidth","borderBottomWidth","borderLeftWidth"]).

    jQuery 3.2,CSS自定义属性(也称为CSS变量)的支持:$("p").css("--custom-property")。请注意,您需要按原样提供属性名称,camelCasing不能像常规CSS属性那样使用。

    例子

    点击div,得到它的背景颜色

    <!DOCTYPE html>
    <html>
    <head>
      <style>
    div { width:60px; height:60px; margin:5px; float:left; }
      </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
     
    <span id="result">&nbsp;</span>
    <div style="background-color:blue;"></div>
    <div style="background-color:rgb(15,99,30);"></div>
     
    <div style="background-color:#123456;"></div>
    <div style="background-color:#f11;"></div>
    <script>
    $("div").click(function () {
      var color = $(this).css("background-color");
      $("#result").html("That div is <span style='color:" +
                         color + ";'>" + color + "</span>.");
    });
     
    </script>
     
    </body>
    </html>
    

    点击div,得到宽度,高度,文本颜色,背景颜色。

    <!DOCTYPE html>
    <html>
    <head>
      <style>
    div { height: 50px; margin: 5px; padding: 5px; float: left; }
     
    #box1 { width: 50px; color: yellow; background-color: blue; }
    #box2 { width: 80px; color: rgb(255,255,255); background-color: rgb(15,99,30); }
    #box3 { width: 40px; color: #fcc; background-color: #123456; }
    #box4 { width: 70px; background-color: #f11; }
    </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
     
    <p id="result">&nbsp;</p>
    <div id="box1">1</div>
    <div id="box2">2</div>
    <div id="box3">3</div>
    <div id="box4">4</div>
    <script>
    $("div").click(function () {
      var html = ["The clicked div has the following styles:"];
     
      var styleProps = $(this).css( ["width", "height", "color", "background-color"] );
      $.each( styleProps, function( prop, value ) {
        html.push( prop + ": " + value );
      });
     
      $( "#result" ).html( html.join( "<br>" ) );
    });
     
    </script>
     
    </body>
    </html>
    
    1
    2
    3
    4

    css(propertyName, value)

    设置每个匹配元素的一个或多个CSS属性。

    .css(propertyName, value)
    • properties类型: PlainObject。一个属性-值配对的对象

    .prop()方法一样,.css()方法使得设置元素的CSS属性快速而又简单。这个方法可以使用任何一个CSS属性名和用空格隔开的值,或者一个“键/值”对对象(JavaScript 对象符号)作为参数。

    另外,jQuery可以同样解析CSS和用multiple-word(用横杠连接的词,比如:background-color)属性的DOM格式。举个例子:jquery能解析.css({'background-color':'#ffe','border-left':'5px solid #ccc'}).css({backgroundColor:'#ffe', borderLeft:'5px solid #ccc'})并且返回正确的值(注意这两条语句的单引号和“-”)。在 DOM 标记法中,属性名可以不使用引号包裹,但是在 CSS 标记法中,如果属性中含有连字符(-)的话,则必须用引号包裹。。

    .css()作为一个设置函数使用的时候,jQuery修改元素的style(样式)属性。例如,$('#mydiv').css('color','green')等价于document.getElementById('mydiv').style.color ='green'。样式属性的值设置为空字符串-例如,$('#mydiv').css('color','')-那么会从元素上移除该属性(若该属性存在的话),该属性之前可能是通过 jQuery 的.css()方法设置的 HTML style 属性,也有可能是通过直接对style属性进行 DOM 操作而被设置的。它不会移除通过 CSS 规则或<style>元素设置的属性。警告:一个值得注意的例外情况是,IE 8及以下版本,删除的简写属性,如边border或者background将完全的删除该元素样式,不管是在样式表或<style>元素中。

    从jQuery1.6开始,.css()接受类似于.animate()的相对值。相对值时以+=或者-=开头的字符串,表示递增或递减当前的值。例如,如果一个元素的左边填充(padding-left)是10px的,.css("padding-left","+=15")将返回总的左填充(padding-left )为25px。

    从 jQuery 1.4开始,.css()让我们传递一个函数给属性值:

    jQuery 3.2,CSS自定义属性(也称为CSS变量)的支持:$("p").css("--custom-property")。请注意,您需要按原样提供属性名称,camelCasing不能像常规CSS属性那样使用。

    $('div.example').css('width', function(index) {
      return index * 50;
    });
    

    这个例子设置一个匹配元素的宽度增加到较大的值。

    注意:如果设置函数没有返回任何东西(例如.function(index, style){}),或者如果返回undefined,当前的值不会改变。只有当某些条件得到满足,选择性的设定值的时后是有用的。

    例子

    通过mouseover事件改变一些段落的颜色为红色。

    <!DOCTYPE html>
    <html>
    <head>
      <style>
      p { color:blue; width:200px; font-size:14px; }
      </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
     
      <p>Just roll the mouse over me.</p>
     
      <p>Or me to see a color change.</p>
     
    <script>
      $("p").mouseover(function () {
        $(this).css("color","red");
      });
    </script>
     
    </body>
    </html>
    

    Just roll the mouse over me.

    Or me to see a color change.

    增加#box 的宽度为200像素

    <!DOCTYPE html>
    <html>
    <head>
      <style>
      #box { background: black; color: snow; width:100px; padding:10px; }
      </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
     
      <div id="box">Click me to grow</div>
     
    <script>
      $("#box").one( "click", function () {
        $( this ).css( "width","+=200" );
      });
    </script>
     
    </body>
    </html>
    
    Click me to grow

    突出段落中点击文本。

    <!DOCTYPE html>
    <html>
    <head>
      <style>
      p { color:blue; font-weight:bold; cursor:pointer; }
      </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
     
    <p>
      Once upon a time there was a man
      who lived in a pizza parlor. This
      man just loved pizza and ate it all
      the time.  He went on to be the
      happiest man in the world.  The end.
    </p>
    <script>
      var words = $("p:first").text().split(" ");
      var text = words.join("</span> <span>");
      $("p:first").html("<span>" + text + "</span>");
      $("span").click(function () {
        $(this).css("background-color","yellow");
      });
     
    </script>
     
    </body>
    </html>
    

    Once upon a time there was a man who lived in a pizza parlor. This man just loved pizza and ate it all the time. He went on to be the happiest man in the world. The end.

    设置所有段落的文本颜色为红色背景为蓝色:

    <!DOCTYPE html>
    <html>
    <head>
      <style>
      p { color:green; }
    </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
     
      <p>Move the mouse over a paragraph.</p>
      <p>Like this one or the one above.</p>
     
    <script>
      $("p").hover(function () {
        $(this).css({'background-color' : 'yellow', 'font-weight' : 'bolder'});
      }, function () {
        var cssObj = {
          'background-color' : '#ddd',
          'font-weight' : '',
          'color' : 'rgb(0,40,244)'
        };
        $(this).css(cssObj);
      });
    </script>
     
    </body>
    </html>
    

    Move the mouse over a paragraph.

    Like this one or the one above.

    当你点击一个div的时候递增他的尺寸

    <!DOCTYPE html>
    <html>
    <head>
      <style>
      div { width: 20px; height: 15px; background-color: #f33; }
      </style>
      <script src="https://www.lanmper.cn/static/js/jquery-3.5.0.js"></script>
    </head>
    <body>
     
      <div>click</div>
      <div>click</div>
     
    <script>
      $("div").click(function() {
        $(this).css({
          width: function(index, value) {
            return parseFloat(value) * 1.2;
          },
          height: function(index, value) {
            return parseFloat(value) * 1.2;
          }
     
        });
      });
    </script>
     
    </body>
    </html>
    
    click
    click

    上篇:toggleClass()