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方法和事件方法用法詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!