属性&CSS操作

属性相关

.val([value])

这是一个读写双用的方法,用来处理input的value,当方法没有参数的时候返回input的value值,当传递了一个参数的时候,方法修改input的value值为参数值

$('input').val()
$('input').val('newValue');

.attr()
.attr(attributeName) 获取元素特定属性的值

var title = $( "em" ).attr( "title" );

.attr(attributeName,value) / .attr(attributesJson) / .attr( attributeName, function(index, attr) )为元素属性赋值

$( "#greatphoto" ).attr( "alt", "Beijing Brush Seller" );

$( "#greatphoto" ).attr({
  alt: "Beijing Brush Seller",
  title: "photo by Kelly Clark"
});

$( "#greatphoto" ).attr( "title", function( i, val ) {
  return val + " - photo by Kelly Clark";
});

.removeAttr()

为匹配的元素集合中的每个元素中移除一个属性(attribute)

.removeAttr() 方法使用原生的 JavaScript removeAttribute() 函数,但是它的优点是可以直接在一个 jQuery 对象上调用该方法,并且它解决了跨浏览器的属性名不同的问题。

$('div').removeAttr('id');

CSS相关

.css()
这是个和attr非常相似的方法,用来处理元素的css

.css(propertyName) / .css(propertyNames)
获取元素style特定property的值

var color = $( this ).css( "background-color" );
var styleProps = $( this ).css([
  "width",
  "height",
  "color",
  "background-color"
]);

.css(propertyName,value) / .css( propertyName, function(index, value) ) / .css( propertiesJson )
设置元素style特定property的值

$( "div.example" ).css( "width", function( index ) {
  return index * 50;
});
$( this ).css( "width", "+=200" );
$( this ).css( "background-color", "yellow" );
$( this ).css({
  "background-color": "yellow",
  "font-weight": "bolder"
});

.addClass(className) / .addClass(function(index,currentClass))
为元素添加class,不是覆盖原class,是追加,也不会检查重复

$( "p" ).addClass( "myClass yourClass" );
$( "ul li" ).addClass(function( index ) {
  return "item-" + index;
});

removeClass([className]) / ,removeClass(function(index,class))
移除元素单个/多个/所有class

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

$( "li:last" ).removeClass(function() {
  return $( this ).prev().attr( "class" );
});

.hasClass(className)

检查元素是否包含某个class,返回true/false

$( "#mydiv" ).hasClass( "foo" )

.toggleClass(className)

toggle是切换的意思,方法用于切换,switch是个bool类型值,这个看例子就明白

<div class="tumble">Some text.</div>

第一次执行

$( "div.tumble" ).toggleClass( "bounce" )
<div class="tumble bounce">Some text.</div>

第二次执行

$( "div.tumble" ).toggleClass( "bounce" )
<div class="tumble">Some text.</div>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 13,090评论 0 3
  • jQuery基础(一)——样式篇 1-2环境搭建 1-3 jQuery HelloWorld体验 $(docume...
    croyance0601阅读 4,722评论 0 8
  • 一、样式篇 第1章 初识jQuery (1)环境搭建 进入官方网站获取最新的版本 http://jquery.co...
    凛0_0阅读 8,796评论 0 44
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 6,130评论 0 2
  • 董沛沛 洛阳 焦点讲师班三期 坚持原创分享第416天 此刻,在开往山东的火车上,又要开启一次学习之旅,和几个伙伴...
    缘源流长阅读 1,371评论 0 0