jQuery学习——CSS

.addClass()

描述: 为每个匹配的元素添加指定的样式类名

值得注意的是这个方法不会替换一个样式类名。它只是简单的添加一个样式类名到元素上。

addClass( function(index, currentClass) )

  • function(index, currentClass)
    类型: Function()
    这个函数返回一个或更多用空格隔开的要增加的样式名。接收index 参数表示元素在匹配集合中的索引位置和html 参数表示元素上原来的 HTML 内容。在函数中this指向匹配元素集合中的当前元素。

对所有匹配的元素可以一次添加多个用空格隔开的样式类名, 像这样:

$("p").addClass("myClass yourClass");

这个方法通常和.removeClass()一起使用,用来切换元素的样式, 像这样:

$("p").removeClass("myClass noClass").addClass("yourClass");

这里, myClass 和 noClass 样式名在所有段落上被移除, 然后 yourClass 被添加。

自 jQuery 1.4开始, .addClass() 方法允许我们通过传递一个用来设置样式类名的函数。

$("ul li:last").addClass(function(index) {
  return "item-" + index;
});

给定一个有2个<li>元素的无序列表,这个例子将在最后一个<li>元素上加上"item-1"样式。

在匹配的元素上加上'selected'和 'highlight' 样式。

$("p:last").addClass("selected highlight");

Pass in a function to .addClass() to add the "green" class to a div that already has a "red" class.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { background: white; }
  .red { background: red; }
  .red.green { background: green; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
 
 <div>This div should be white</div>
 <div class="red">This div will be green because it now has the "green" and "red" classes.
   It would be red if the addClass function failed.</div>
 <div>This div should be white</div>
 <p>There are zero green divs</p>
 
<script>
  $("div").addClass(function(index, currentClass) {
    var addedClass;
 
    if ( currentClass === "red" ) {
      addedClass = "green";
      $("p").text("There is one green div");
    }
 
    return addedClass;
  });
</script>
 
</body>
</html>

.css()

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

Contents:

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

 

.css()方法可以非常方便地获取匹配的元素集合中第一个元素的样式属性值, 对于某些属性而言,浏览器访问样式属性的方式是不同的,该方法对于取得这些属性是非常方便的(例如, 某些属性在标准浏览器下是通过的getComputedStyle() 方法取得的,而在Internet Explorer下是通过currentStyle 和 runtimeStyle属性取得的)并且,某些特定的属性,不同浏览器的写法不一。举个例子, 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" ]).

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

<!DOCTYPE html>
<html>
<head>
  <style>
div { width:60px; height:60px; margin:5px; float:left; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.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="http://code.jquery.com/jquery-latest.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>

.css( propertyName, value )

  • .css( propertyName, value )

    • propertyName
      类型:String
      一个CSS属性名
    • value
      类型:String,Number
      设置这个CSS属性的值
  • 添加的版本: 1.4.css( propertyName, function(index, value) )

    • propertyName
      类型:String
      一个CSS属性名
    • function(index, value)
      类型:Function()
      一个返回设置值的函数。this 是当前元素。接收index 参数表示元素在匹配集合中的索引位置和html 参数表示元素上原来的 HTML 内容。
  • 添加的版本: 1.0css( properties )

    • 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() 让我们传递一个函数给属性值:

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

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

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

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

<script>
  $("p").mouseover(function () {
    $(this).css("color","red");
  });
</script>

增加#box 的宽度为200像素

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

突出段落中点击文本。

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:blue; font-weight:bold; cursor:pointer; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.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>

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

<!DOCTYPE html>
<html>
<head>
  <style>
  p { color:green; }
</style>
  <script src="http://code.jquery.com/jquery-latest.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>

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

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

jQuery.cssHooks

描述: 直接向 jQuery 中添加钩子,用于覆盖设置或获取特定 CSS 属性时的方法,目的是为了标准化 CSS 属性名或创建自定义属性。

$.cssHooks 对象提供了一种方法通过定义函数来获取和设置特定的CSS值的方法。  它也可以被用来创建新的cssHooks以标准化CSS3功能,如框阴影和渐变。

例如,某些版本基于Webkit的浏览器需要-webkit-border-radius属性来设置元素的border-radius,而早期的Firefox版本使用-moz-border-radius属性。一个CSS hook 可以标准化这些供应商前缀的属性,让.css() 接受一个单一的,标准的属性的名称(border-radius,或用DOM属性的语法,borderRadius)。

除了提供了对特定样式的处理可以采用更加细致的控制外,  $.cssHooks也扩展了.animate() 方法上可用的属性。

定义一个新的css hook十分简单。下面的模板可以方便您创建自己的 cssHook:

(function($) {
  // first, check to see if cssHooks are supported
  if ( !$.cssHooks ) {
    // if not, output an error message
    throw("jQuery 1.4.3 or above is required for this plugin to work");
    return;
  }
 
  // Wrap in a document ready call, because jQuery writes
  // cssHooks at this time and will blow away your functions
  // if they exist.
  $(function () {
    $.cssHooks["someCSSProp"] = {
      get: function( elem, computed, extra ) {
        // handle getting the CSS property
      },
      set: function( elem, value ) {
        // handle setting the CSS value
      }
    };
  });
})(jQuery);

.

.

.

.

待续

.hasClass()

 描述: 确定任何一个匹配元素是否有被分配给定的(样式)类。

在匹配的元素上寻找 'selected' 样式。

<!DOCTYPE html>
<html>
<head>
  <style>
  p { margin: 8px; font-size:16px; }
  .selected { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
 
  <p>This paragraph is black and is the first paragraph.</p>
  <p class="selected">This paragraph is red and is the second paragraph.</p>
 
  <div id="result1">First paragraph has selected class: </div>
  <div id="result2">Second paragraph has selected class: </div>
  <div id="result3">At least one paragraph has selected class: </div>
<script>
$("div#result1").append($("p:first").hasClass("selected").toString());
$("div#result2").append($("p:last").hasClass("selected").toString());
$("div#result3").append($("p").hasClass("selected").toString());
</script>
 
</body>
</html>

.removeClass()

描述: 移除集合中每个匹配元素上一个,多个或全部样式。

如果一个样式类名作为一个参数,只有这样式类会被从匹配的元素集合中删除 。 如果没有样式名作为参数,那么所有的样式类将被移除。

从所有匹配的每个元素中同时移除多个用空格隔开的样式类 

从匹配的元素中移除“blue”和“under”样式类。

<!DOCTYPE html>
<html>
<head>
  <style>
  p { margin: 4px; font-size:16px; font-weight:bolder; }
  .blue { color:blue; }
  .under { text-decoration:underline; }
  .highlight { background:yellow; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p class="blue under">Hello</p>
 
  <p class="blue under highlight">and</p>
  <p class="blue under">then</p>
  <p class="blue under">Goodbye</p>
<script>$("p:odd").removeClass("blue under");</script>
 
</body>
</html>

.toggleClass()

描述: 在匹配的元素集合中的每个元素上添加或删除一个或多个样式类,取决于这个样式类是否存在或值切换属性。即:如果存在(不存在)就删除(添加)一个类。

当点击段落的是有切换 'highlight' 样式类

<!DOCTYPE html>
<html>
<head>
  <style>
 
  p { margin: 4px; font-size:16px; font-weight:bolder;
      cursor:pointer; }
  .blue { color:blue; }
  .highlight { background:yellow; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p class="blue">Click to toggle</p>
  <p class="blue highlight">highlight</p>
  <p class="blue">on these</p>
  <p class="blue">paragraphs</p>
<script>
    $("p").click(function () {
      $(this).toggleClass("highlight");
    });
</script>
 
</body>
</html>

每当第三次点击段落的时候添加 "highlight" 样式类, 第一次和第二次点击的时候移除 "highlight" 样式类

<!DOCTYPE html>
<html>
<head>
  <style>
  p { margin: 4px; font-size:16px; font-weight:bolder;
      cursor:pointer; }
  .blue { color:blue; }
  .highlight { background:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p class="blue">Click to toggle (<span>clicks: 0</span>)</p>
  <p class="blue highlight">highlight (<span>clicks: 0</span>)</p>
  <p class="blue">on these (<span>clicks: 0</span>)</p>
 
  <p class="blue">paragraphs (<span>clicks: 0</span>)</p>
<script>
var count = 0;
$("p").each(function() {
  var $thisParagraph = $(this);
  var count = 0;
  $thisParagraph.click(function() {
    count++;
    $thisParagraph.find("span").text('clicks: ' + count);
    $thisParagraph.toggleClass("highlight", count % 3 == 0);
  });
});
 
</script>
 
</body>
</html>
原文地址:https://www.cnblogs.com/pilee/p/3472004.html