`

自定义Jquery插件方法

阅读更多
<html>
	<head>
		<title>jquery plugins</title>
		<style type="text/css">
		#main{
		   width:300px;
		   height:120px;
		}
		.main_box{
		  width:120px;
		  height:100px;
		  background:#CCC;
		  margin:5px;
		  float:left;
		  color:#fff;
		  text-align:center;
		}
		
		.test{
			background:#000;
		}
		
		.test2{
			background:#888;
		}
		</style>
		<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
		<script type="text/javascript">
		<!--
		//定义作用域:定义一个JQuery插件,首先要把这个插件的代码放在一个不受外界干扰的地方。
		(function($){
			//内部方法
			var setFontColor = function(obj,color){
				$(obj).css({"color":color});
			}
			//定义插件
			$.fn.setBackGround = function (options) {
				//默认参数
				var defaults = {
					className:'test'
				};
				//覆盖defaults中的对应属性,并替换options。可以理解成合并覆盖
				options = $.extend(defaults, options);
				
				$(this).addClass(options.className);
				//支持链接调用
				return this.each(function(){
					setFontColor(this,"red");
				});
			}
		
		})(jQuery);
		
		$(document).ready(function(){
		   //调用方式
		   //#main
		   $(".main_box").setBackGround({className:'test2'})//插件调用
		   .css({ "border-width": "1", "border-color": "red", "border-bottom-style": "dotted" });//链接调用
		});
		//-->
		</script>
	</head>
	<body>
		<div id="main">
			<div class="main_box">a</div>
			<div class="main_box">b</div>
		<div>
	</body>
</html>
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics