JSFiddle - React, Tailwind, and code Playground
HTML
<ul>
<li>001</li>
<li>002</li>
<li>003</li>
<li>004</li>
<li>005</li>
<li>006</li>
<li>007</li>
</ul>
JavaScript
$(document).ready(function(){
$('ul').ChangeBg();
});
/**
* @description 给某标签下的所有奇数行的子元素(注意:是子元素,而非后代元素),
* 设置背景颜色,同时给所有子元素增加鼠标移入移出时更改背景和字体颜色的事件。
* @param {string} bgCol 奇数行要设置的背景颜色,默认为'#EEE'
* @param {string} chBgCl 鼠标移入时背景颜色,默认为'#0066CC'
* @param {string} chCol 鼠标移入时的字体颜色,默认为'#FFF'
* @returns void
* @author Yuanqi<[email protected]>
*/
(function($) {
$.fn.extend({
"ChangeBg": function(bgCol, chBgCl, chCol) {
var $bgCol = bgCol || '#EEE',
$chBgCl = chBgCl || '#0066CC',
$chCol = chCol || '#FFF';
var $childs = $(this).children(),
$bfBg,
$bfCl;
for (var i = $childs.length - 1; i >= 0; i--) {
$childs[i].index = i;
if (i % 2 === 0) {
$($childs[i]).css('backgroundColor', $bgCol); // 奇数行的li更改背景颜色
}
$($childs[i]).mouseover(
function() {
bfBg = $(this).css('backgroundColor');
bfCl = $(this).css('color');
$(this).css({
backgroundColor: $chBgCl, // 鼠标移入时更改的背景颜色
color: $chCol // 鼠标移入时更改的字体颜色
});
}
);
$($childs[i]).mouseout(
function(pro) {
$(this).css({
backgroundColor: bfBg,
color: bfCl
});
}
);
}
}
});
})(jQuery);