自定义简单的jquery的插件

首先jquery的文件是要导入的

color.js

//改变背景色的插件 
//$.fn.
(function($) {
	/*1.方式一
	 * 
	 * $.fn.changeColor=function(){
		if
		$(this).css("background-color","yellow").css("color","red");
		
		return $(this)
	}*/

	//方式二
	$.fn.extend({
		//参数里面是一个对象,键值对,传入向下文环境
		changeDom: function(option) {
			var defaulta = {
				ptext: "1111",
				bgColor: "yellow",
				fColor: "green"
			}
			if(typeof(option.ptext) == "undefined" || option.ptext.length == 0) {
				$(this).html(defaulta.ptext);
			} else {
				$(this).html(option.ptext);
			}
			if(typeof(option.bgColor) == "undefined" || option.bgColor.length == 0) {
				$(this).css("background-color", defaulta.bgColor);
			} else {
				$(this).css("background-color", option.bgColor);
			}
			if(typeof(option.fColor) == "undefined" || option.fColor.length == 0) {
				$(this).css("color", defaulta.fColor);
			} else {
				$(this).css("color", option.fColor);
			}
		}

	})
})(jQuery)

插件的意义是当用户调用这个插件时没有插入值就用有默认值,插入值就用用户定义的颜色

首先要引入插件
<script src="color.js"></script>


		var option={
			ptext:"",
			bgColor:"red",
			fColor:""
		}
	
		$(document).ready(
			function(){
			$("#div1").changeDom(option);
			//$("#div2").changeDom2();
		})

猜你喜欢

转载自blog.csdn.net/qq_40183281/article/details/90577743