========== jQuery 插件的编写
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div {
100px;
height: 100px;
border: 5px solid black;
}
</style>
</head>
<body>
<div></div>
<div></div>
<script src="./lib/jquery-3.4.1.min.js"></script>
<script>
//jquery插件的编写:4点
// 1. 使用立即执行函数
(function ($) {
//确保$就是jQuery
// 2. $.fn.extend添加插件.
// 将randomColor添加到jQuery.prototype上了
// 实际上$.fn === jQuery.prototype
$.fn.extend({
randomColor: function () {
// console.log('randomColor被调用了');
// this就是jquery的实例(伪数组)
// 3. 要遍历jQuery对象中的每个DOM节点
// let random = () => '#' + ('000000' + Math.floor(Math.random() * 0xFFFFFF).toString(16)).slice(-6)
// let random = function () {
// //0x开头的数字,表示16进制的数字
// let num = Math.floor(Math.random() * 0xFFFFFF)
// //将num转换为16进制字符串
// num = num.toString(16)
// //将num前面补零,保证至少6位
// num = ('000000' + num).slice(-6)
// return '#' + num;
// }
let random = function () {
var r = Math.floor(Math.random() * 256)
var g = Math.floor(Math.random() * 256)
var b = Math.floor(Math.random() * 256)
return `rgb(${r},${g},${b})`
}
for (var i = 0; i < this.length; i++) {
//随机设定每个元素的背景色
$(this[i]).css({
backgroundColor: random()
})
}
// 4. 要实现链式操作
return this;
}
})
})(jQuery)
$('div').randomColor().css({
borderColor: 'purple'
})
</script>
</body>
</html>