第05章 基础 DOM 和 CSS 操作(中)

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>基础 DOM 和 CSS 操作</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="demo.js"></script>
<link type="text/css" rel="stylesheet" href="style.css" />
</head>
<body>

<div title="demo" style="color:#c00; width:600px;">
	<strong>http://onestopweb.cn/</strong>
</div>

<div title="demo" class="green">
	<strong>http://onestopweb.cn/</strong>
</div>

</body>
</html>

style.css

.red{ color:red;}
.green{ color:green;}
.bg{ background-color:#ccc;}
.size{ font-size:20px;}

demo.js

$(function(){
	//alert($('div').css('color'));
	//$('div').css('color','red');
	var box = $('div').css(['color','width','height']);
	/*
	
	for(var i in box){
		alert(i+':'+box[i]);
	}
	$.each(box,function(attr,value){
		alert(attr+':'+value);
	});
	
	//alert($('div')[0]);
	$('div').each(function(index,element){
		alert(index+':'+element);
	});
	//$('div').css('color','red').css('background-color','#ccc');
	$('div').css({
		'color':'red',
		'background-color':'#ddd',
		'width':'200px',
		'height':'30px'
	});
	$('div').css('width',function(index,value){
		//局部操作,很舒服
		return parseInt(value)-500+'px';
	});
	
	//$('div').addClass('red');
	//$('div').addClass('bg');
	//$('div').addClass('red bg size');
	//$('div').removeClass('bg');
	//$('div').removeClass('red size');
	$('div').click(function(){
		$(this).toggleClass('red size');//两个样式之间的切换,默认样式和指定样式的切换
	});
	
	var count =0;
	$('div').click(function(){
		$(this).toggleClass('red size',count++%2==0);//频率的问题
	});	
	$('div').click(function(){
		//这里只是 click 的局部,而又是 toggle 的全局
		$(this).toggleClass('red');
		if($(this).hasClass('red')){
			$(this).removeClass('green')
		}else{
			//$(this).toggleClass('green');
			$(this).addClass('green');
		}
	});
	$('div').click(function(){
		$(this).toggleClass(function(){
			return $(this).hasClass('red')?'green':'red';
		});
	});
	
	$('div').click(function(){
		$(this).toggleClass(function(){
			//局部
			if($(this).hasClass('red')){
				$(this).removeClass('red');
				return 'green';
			}else{
				$(this).removeClass('green');
				return 'red';
			}
		});
	});
	*/
	
	var count = 0;
	$(document).click(function(){
		$('div').toggleClass(function(index,className,switchBool){
			alert(index+':'+className+':'+switchBool);
			//局部
			if($(this).hasClass('red')){
				$(this).removeClass('red');
				return 'green';
			}else{
				$(this).removeClass('green');
				return 'red';
			}
		},count++%2==0);
	});
	
});

猜你喜欢

转载自onestopweb.iteye.com/blog/2223864