<!doctype html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width,initial-scale=1">
	<title>jq-jquery源码简化版本</title>
</head>
<body>
	<div id="dd"></div>
	<div class="demo">1</div>
	<div class="demo">2</div>
<script>
	(function () {
		function jQuery(selector) {
			// 无new构造
			return new jQuery.prototype.init(selector);
		}

		jQuery.prototype.init = function (selector) {
			// 通过id, class选择元素
			// id, class
			this.length = 0;
			var dom = '';
			if (typeof selector == 'string' && selector.indexOf('.') != -1) {
				selector = selector.slice(1);
				dom = document.getElementsByClassName(selector);
			} else if ( typeof selector == "string" && selector.indexOf('#') != -1) {
				selector = selector.slice(1);
				dom = document.getElementById(selector);
			}
			if (dom.length == undefined) {
				this[0] = dom;
				this.length++;
			} else {
				for (var i = 0; i < dom.length; i++) {
					this[i] = dom[i];
					this.length++;
				}
			}
		}
                // css方法源码简易版
		jQuery.prototype.css = function (config) {
			for (var i = 0; i < this.length; i++) {
				for ( var attr in config ) {
					this[i].style[attr] = config[attr];
				}
			}
			return this;
		}
		jQuery.prototype.init.prototype = jQuery.prototype;

		window.$ = window.jQuery = jQuery;
	}())

	console.log($('.demo'));
	$('.demo')
		.css({
			marginBottom: '10px', 
			width: '100px', 
			height: '100px', 
			backgroundColor: 'red'
		})
		.css({'color': 'white', 'font-size': '25px'});
</script>
</body>
</html>

博主联系方式:

  • 微信:34419369
  • QQ: 34419369
  • 公众号:前方录
  • 有什么不懂的地方欢迎联系我,帮到你是我会很开心

Leave a Reply

电子邮件地址不会被公开。 必填项已用*标注