jQuery基礎教程——樣式與動畫

一、使用.css()方法修改內聯CSS

     1、jQuery既可以解釋字符版的CSS表示法(如background-color),也可以解釋駝峯大小寫形式(camel-cased)的DOM表示法(如backgroundColor)。

     2、.css()方法能夠接受的參數有兩種,一種是爲它傳遞一個單獨的樣式屬性和值,另一種是爲它傳遞一個有屬性-值對構成的映射。

          //單個屬性及其值

          .css('property','value')

         //屬性-值對構成的映射

        .css({   property1:'value1',

                      'property2':'value2'

         })

       PS:數字值不需要加引號而字符串值需要加引號。由於屬性名是字符串,所以屬性通常是需要加引號的。但是,如果對象字面量中的屬性名是有效的javascript標示符,比如使用駝峯大小寫形式的DOM表示法時,則可以省略引號。

      以下是一個通過按鈕逐漸增大文字字體大小的效果。

<!DOCTYPE html>
<html>
<head>
<!-- jquery mix NIE (最新版本)-->
<script charset="gb2312" src="http://res.nie.netease.com/comm/js/jquery(mixNIE).last.js"></script>
<body>
<div id="switcher" style="width:200px;">
    <div class="label">Text Size</div>
    <button id="switcher-default">Default</button>
    <button id="switcher-large">Bigger</button>
    <button id="switcher-small">Smaller</button>
</div>
<div class="speech">
    <p>Fourscore and seven years ago our fathers brought forth on this continer a new nation,conceived in liberty,and dedicated to the proposition that all men are created equal.</p>
<p style="border:1px solid red;">Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battlefield of that war. We have come to dedicate a portion of that field as a final resting-place for those who here gave their lives that the nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we cannot dedicate, we cannot consecrate, we cannot hallow, this ground.</p>
    <a href="#" class="more">read more</a>
    <p>The brave men, living and dead, who struggled here have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember, what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced.</p>
    <p>It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom and that government of the people, by the people, for the people, shall not perish from the earth.</p>
</div>
</body></html>


以下是jQuery代碼清單:

<script type="text/javascript">
$(document).ready(function(){
	var $speech = $('div.speech');
	var defaultSize = $speech.css('fontSize');
	$('#switcher button').click(function() {
		var num=parseFloat($speech.css('fontSize'));//獲取當前字體的大小。通過parseFloat()函數只取得字體大小屬性中的數值部分。parseFloat()函數會在一個字符串中從左到右地查找一個浮點(十進制)數。
		switch (this.id) {
			case 'switcher-large':
				num *= 1.4;
				break;
			case 'switcher-small':
				num /= 1.4;
				break;
			default:
				num = parseFloat(defaultSize);
		}
		$speech.css('fontSize',num+'px');
	});
});
</script>

 二、基本的隱藏和顯示。

1、基本的隱藏和顯示就是不帶參數的.hide()和.show()。它的好處就是有記憶功能。可以記住元素最初的display屬性。(inline或者block)。

2、有效果和速度的就是參數的.hide()和.show()。.show('speed')方法會同時從上到下增大元素高度,從左到右增大元素寬度,從0到1增加元素的不透明度。參數有三個預設值slow0.6秒、normal0.4秒、fast0.2秒或者是毫秒數值.show(850);

3、淡入和淡出的效果就是.fadeIn()和.fadeOut()。

4、滑上和滑下的效果就是.slideDown()和.slideUp()。

5、實現複合效果可以使用.toggle()方法。包括顯示和隱藏,還有.slideToggle();方法。


以下附上javascript代碼:

$(document).ready(function(){
	var $firstPara=$('p').eq(1);//這裏的.eq()方法返回jQuery對象,其中包含一個元素(索引從0開始)。
	$firstPara.hide();
	$('a.more').click(function(){
		if($firstPara.is(':hidden')){
			$firstPara.slideDown('slow');
			$(this).text('read less');//使用.text()方法修改元素中的文本。
		}else{
			$firstPara.slideUp('slow');
			$(this).text('read more');
		}
	return false;//避免鏈接的默認操作。
	});
});

或者實現複合效果可以使用.toggle()方法。

$(document).ready(function(){
	var $firstPara=$('p').eq(1);//這裏的.eq()方法返回jQuery對象,其中包含一個元素(索引從0開始)。
	$firstPara.hide();
	$('a.more').click(function(){
		$firstPara.slideToggle('slow');
        var $link=$(this);
		if($link.text()=='read more'){
			$link.text('read less');//使用.text()方法修改元素中的文本。
		}else{
			$link.text('read more');
		}
		return false;//避免鏈接的默認操作。
	});
});

 三、用.animate()方法創建自定義動畫。

1、第一種形式有4個參數

a、一個包含樣式屬性及值的映射

b、可選的速度參數

c、可選的緩動

d、可選的回調函數

.animate({property1:'value1',property2:'value2'},speed,easing,function(){

alert('The animation is finished.');

});

2、第二種形式接受兩個參數。

.animate({properies},{options})

PS:第二種是把第一種形式的第2~4個參數封裝在了另一個映射中,同時添加了兩個選項。

查詢:http://www.w3school.com.cn/jquery/effect_animate.asp

下面使用第一種形式手工創建效果。(也可以使用其他CSS屬性,如:left、top、fontsize、margin、padding和borderWidth。)

$(document).ready(function(){
	$firstPara=$('p').eq(1);//這裏的.eq()方法返回jQuery對象,其中包含一個元素(索引從0開始)。
	$firstPara.hide();
	$('a.more').click(function(){
		$firstPara.animate({height:'toggle',opacity:'toggle'},'slow');
        var $link=$(this);
		if($link.text()=='read more'){
			$link.text('read less');//使用.text()方法修改元素中的文本。
		}else{
			$link.text('read more');
		}
		return false;//避免鏈接的默認操作。
	});
});

或者這樣的效果:讓該項從頁面左側移動到右側的同時,高度增加20像素並使其邊框寬度增加到5像素。

$(document).ready(function(){
	$('div.label').click(function(){
		var paraWidth = $('div.speech p').outerWidth();
		var $switcher = $(this).parent();
		var switcherWidth = $switcher.outerWidth();
		$switcher.css({
			position:'relative'
		}).animate({
			borderWidth:'5px',
			left:paraWidth - switcherWidth,
			height:'+=20px'
		},'slow');
		
	});
});

 四、關於併發與排隊效果

1、處理一組元素,分別將效果代碼放在.animate()方法中連綴起來即可。

$(document).ready(function(){
	$('div.label').click(function(){
	var paraWidth = $('div.speech p').outerWidth();
	var $switcher = $(this).parent();
	var switcherWidth = $switcher.outerWidth();
	$switcher
		.css({position:'relative'})
		.animate({left:paraWidth -switcherWidth},'slow')
		.animate({height:'+=20px')},'slow')
		.animate({borderWidth:'5px'},'slow');
	});
});

2、處理一組元素,效果代碼連綴起來,但是其中兩個動畫同時進行。下面是全部順序播放與兩個連綴在一起的代碼。

$('div.label').click(function() {
    var paraWidth = $('div.speech p').outerWidth();
    var $switcher = $(this).parent();
    var switcherWidth = $switcher.outerWidth();
    $switcher
      .css({position: 'relative'})
      .fadeTo('fast', 0.5)
      .animate({left: paraWidth - switcherWidth}, 'slow')
      .fadeTo('slow', 1.0)
      .slideUp('slow')
      .slideDown('slow');
  });
 $('div.label').click(function() {
    var paraWidth = $('div.speech p').outerWidth();
    var $switcher = $(this).parent();
    var switcherWidth = $switcher.outerWidth();
    $switcher
      .css({position: 'relative'})
      .fadeTo('fast', 0.5)
      .animate({
        left: paraWidth - switcherWidth
      }, {
        duration: 'slow',
        queue: false
      })

      .fadeTo('slow', 1.0)
      .slideUp('slow')
      .slideDown('slow');
  });

PS:第二個參數(即選項映射)包含了queue選項,把該選項設置爲false即可讓當前動畫與前一個動畫同時開始。

手工安排隊列:排隊不能自動應用到其他的非效果方法,如.css()方法。把非效果方法添加到隊列中的一種方式,就是使用.queue()方法。添加的.next()方法可以讓隊列在中斷的地方在接續起來。如下代碼所示:

$('div.label').click(function() {
    var paraWidth = $('div.speech p').outerWidth();
    var $switcher = $(this).parent();
    var switcherWidth = $switcher.outerWidth();
    $switcher
		.css({position: 'relative'})
		.fadeTo('fast', 0.5)
		.animate({
			left: paraWidth - switcherWidth
		}, {
			duration: 'slow',
			queue: false
		})
		.fadeTo('slow', 1.0)
		.slideUp('slow')
		.queue(function(next) {
			$switcher.css({backgroundColor: '#f00'});
			next();
		})
		.slideDown('slow');
});

2、處理多組元素

a、多組元素的動畫同時發生:

$(document).ready(function(){
	$('p').eq(2)
		.css('border', '1px solid #333')
		.click(function() {
			$(this).slideUp('slow').next().slideDown('slow');
		});
	$('p').eq(3).css('backgroundColor', '#ccc').hide();
 });

b、爲了對不同元素上的效果實現排隊,jQuery爲每個效果方法都提供了回調函數。同我們在事件處理程序和.queue()方法中看到的一樣,回調函數就是作爲方法的參數傳遞的一個普通函數。在效果方法中,它們是方法的最後一個參數。

$(document).ready(function(){
	$('p').eq(2)
		.css('border', '1px solid #333')
		.click(function() {
		$(this).next().slideDown('slow', function() {
			$(this).slideUp('slow');
		});
		});
	$('p').eq(3).css('backgroundColor', '#ccc').hide();
});
但是,我們需要注意的是,必選搞清楚要滑上的到底是哪個段落。因爲回調函數位於.slideDown()方法中,所以$(this)得環境已經發生了改變。現在,$(this)已經不再是指向.click()的第三個段落了——由於.slideDown()方法是通過$(this).next()調用的,所以該方法中的一切現在都將$(this)視爲下一個同輩元素,即第四個段落。因而,如果在回調函數中放入$(this).slideUp('slow'),那麼我們最終還會把剛剛顯示出來的段落給隱藏起來。

解決方法就是:將$(this)先保存在一個變量中。比如:var $ clickItem = $(this)。

$(document).ready(function(){
	$('p').eq(2)
		.css('border', '1px solid #333')
		.click(function() {
		var $clickedItem = $(this);
		$clickedItem.next().slideDown('slow', function() {
			$clickedItem.slideUp('slow');
		});
		});
	$('p').eq(3).css('backgroundColor', '#ccc').hide();
});

簡單概括:

  (1)、一組元素上的效果。

A、當在一個.animate()方法中以多個屬性的方式用時,是同時發生的。

B、當以方法連綴的形式應用時,是按順序發生的(排隊效果)——除非queue選項值爲false。

(2)、多組元素上的效果。

A、默認情況下是同時發生的。

B、當在另一個效果方法或者在.queue()方法的回調函數中應用時,是按順序發生的(排隊效果)。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章