上代码:
<!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.0">
<title>Document</title>
<style>
h2 {
color: red;
}
#box {
user-select: none;
}
#box>span {
width: 100px;
line-height: 80px;
text-align: center;
border: 2px solid black;
color: gray;
margin: 0 10px 10px 0;
display: inline-block;
border-radius: 4px;
}
#box>span.active {
color: rgb(255, 10, 10);
border-color: red;
}
</style>
</head>
<body>
<h2>4899</h2>
<div id="box">
<!-- 自定义属性存储价格 -->
<span data-price="4899" class="active">12+256</span>
<span data-price="3999">8+128</span>
<span data-price="3699">16+1024</span>
<span data-price="4399">12+256</span>
</div>
<script type="text/javascript" src="./vendor/jquery-3.6.0.js"></script>
<script type="text/javascript">
// 找到元素来操作
$('#box span').click(function() {
// 给点击的项目添加active兄弟项目删除
// this代表原生dom元素
// this -钢铁侠 $(this)钢铁侠穿上铁甲和不穿铁甲
$(this).addClass('active').siblings().removeClass('active');
// 给点击项目加上效果,然后去掉其他项目的‘active’的效果
// innerhtml/innerText
const price = $(this).data('price')
$('h2').html(price)
})
</script>
</body>
</html>