假如有5个用div做的按钮,互为兄弟元素。默认第一个是选中状态,背景色为红色,
其余四个是未选中状态,背景色为灰色。
每个按钮处于选中状态时背景色都不同,
例如第一个是红色,第二个是蓝色,第三个是粉色,以此类推。
未选中状态下背景色都为灰色。
我需要在这几个按钮中的某个被点击后,怎样才能确定是哪个被点击了,
并设置相对应的颜色呢?
<!DOCTYPE html>
<html lang="cn">
<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>
</head>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<style>
.main{
width: 1200px;
margin: 200px auto;
}
ul li{
width: 150px;
height:60px;
display: inline-block;
background: #eee;
color: #000;
text-align:center;
line-height: 60px;
cursor: pointer;
}
ul li:first-child{
background: red;
}
</style>
<body>
<div class="main">
<ul>
<li>按钮1</li>
<li>按钮2</li>
<li>按钮3</li>
<li>按钮4</li>
<li>按钮5</li>
</ul>
</div>
</body>
<script>
var colorList = ['red','blue','yellow','gold','green']
$("ul li").click(function(){
var index = $(this).index()
$(this).parent().find('li').css("background-color",'#eee')
$(this).css("background-color",colorList[index])
})
</script>
</html>
https://blog.csdn.net/weixin_42063951/article/details/99742258
互为兄弟元素的话可以用jquery的$(this).index()获取当前元素在其父元素中的索引值。
比如:
$(this).css("backgroundColor",["#f00","#ff0","#0ff","#00f"][$(this).index()]);
或者在css中用nth-child()规定第几个div选中时的样式
div.select:nth-child(1) { background-color: #f00; }
div.select:nth-child(2) { background-color: #0f0; }
div.select:nth-child(3) { background-color: #00f; }
之后在js中只要设置 元素的className 为 select 就可以了
如何做到点击一张照片,出来三个button按钮,然后点击其中一个button按钮,出来一段文字