jquery中的css方法和事件方法用法详解
CSS方法
.hasClass(calssName) 检查元素是否包含某个class,返回true/false
$( "#mydiv" ).hasClass( "foo" )
.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" ); });
.toggleClass(className) /.toggleClass(className,switch) / .toggleClass([switch]) / .toggleClass( function(index, class, switch) [, switch ] ) 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>
$( "#foo" ).toggleClass( className, addOrRemove );// 两种写法意思一样if ( addOrRemove ) { $( "#foo" ).addClass( className ); } else { $( "#foo" ).removeClass( className ); }
$( "div.foo" ).toggleClass(function() { if ( $( this ).parent().is( ".bar" ) ) { return "happy"; } else { return "sad"; } });
.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" });
事件方法
.bind( eventType [, eventData ], handler(eventObject) ) 绑定事件处理程序,这个经常用,不多解释
$( "#foo" ).bind( "click", function() { alert( "User clicked on 'foo.'" ); });
.delegate( selector, eventType, handler(eventObject) ) 这个看官方解释吧
Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.
$( "table" ).on( "click", "td", function() {//这样把td的click事件处理程序绑在table上 $( this ).toggleClass( "chosen" ); });
.on( events [, selector ] [, data ], handler(eventObject) ) 1.7后推荐使用,取代bind、live、delegate
$( "#dataTable tbody" ).on( "click", "tr", function() { alert( $( this ).text() ); });
.trigger( eventType [, extraParameters ] ) JavaScript出发元素绑定事件
$( "#foo" ).trigger( "click" );
.toggle( [duration ] [, complete ] ) / .toggle( options ) 隐藏或显示元素
$( ".target" ).toggle(); $( "#clickme" ).click(function() { $( "#book" ).toggle( "slow", function() { // Animation complete. }); });
以上就是jquery中的css方法和事件方法用法详解的详细内容,更多请关注其它相关文章!
上一篇: 如何更好的使用jQuery的常用方法总结
下一篇: 使用css和js实现网页选项卡的效果