点按钮换色
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.changeRed{
background-color:red;
}
</style>
</head>
<body>
<ul>
<li >Hello1</li>
<li>Hello2</li>
<li>Hello3</li>
<li>Hello4</li>
<li>Hello5</li>
<li>Hello6</li>
<li>Hello7</li>
<li>Hello8</li>
<li>Hello9</li>
<li>Hello10</li>
</ul>
<button id="bt1" onclick="arr()">点我</button>
<script type="text/javascript" src="jquery-3.6.0.min.js">
</script>
<script type="text/javascript">
$(function(){
$("ul>li:first").addClass("changeRed");
})
function arr(){
var top= $("ul>li:first");
while(true){
// 判断第一个是否有颜色
if (top.hasClass("changeRed")) {
// 改变第一个颜色
top.toggleClass("changeRed");
// 如果到最后一个
if(top.next().length==0){
// 给top重新标记为第一个
top= $("ul>li:first");
// 给第一个赋值
top.toggleClass("changeRed");
break;
}
// 改变第二个颜色
top.next().toggleClass("changeRed");
break;
} else{
// 递归找下一个判定
top=top.next();
}
}
}
</script>
</body>
</html>
实现效果
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.lired{
background-color: red;
}
</style>
</head>
<body>
<ul>
<li class="lired">Hello1</li>
<li>Hello2</li>
<li>Hello3</li>
<li>Hello4</li>
<li>Hello5</li>
<li>Hello6</li>
<li>Hello7</li>
<li>Hello8</li>
<li>Hello9</li>
<li>Hello10</li>
</ul>
<button id="bt1" onclick="arr()">点我</button>
<script type="text/javascript" src="jquery-3.6.0.min.js">
</script>
<script type="text/javascript">
var count=0;
function arr(){
// $("ul>li:first").toggleClass("lired");
// var ss= $("ul>li:first");
// var rr=$("ul>li");
// $("ul>li:first").next().toggleClass("lired");
// $("ul>li:first").toggleClass("lired");
$("ul>li:eq("+count+")").removeClass();
$("ul>li:eq("+(count+1)+")").addClass("lired");
count++;
if(count==10){
$("ul>li:eq(0)").addClass("lired");
count=0;
}
}
</script>
</body>
</html>
第三种数组
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>第三种方式</title>
<style>
.lired{
background-color: red;
}
</style>
</head>
<body>
<ul>
<li>Hello1</li>
<li>Hello2</li>
<li>Hello3</li>
<li>Hello4</li>
<li>Hello5</li>
<li>Hello6</li>
<li>Hello7</li>
<li>Hello8</li>
<li>Hello9</li>
<li>Hello10</li>
</ul>
<button id="bt1" onclick="arr()">点我</button>
<script type="text/javascript" src="jquery-3.6.0.min.js">
</script>
<script type="text/javascript">
var count=0;
var temp;
function arr(){
// 定义一个数组存放颜色
var ayy =["red","white","white","white","white","white","white","white","white","white"] ;
// 交换颜色位置
temp=ayy[0];
ayy[0]=ayy[count];
ayy[count]=temp;
// 使用each遍历 i是下标
$("ul>li").each(function(i,domEle){
// domEle动态打印每个元素颜色
$(domEle).css("background-color",ayy[i]);
})
// 自增
count++;
// 判断第10次自动回位
if(count==10){
count=0;
}
}
</script>
</body>
</html>
版权声明:本文为just_learing原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。