利用index实现:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{display:none;} .item{ height: 38px; 800px; border: 1px solid #dddddd; margin: 0 auto; } .item .item-content{ float: left; line-height: 38px; padding: 0 15px; border-right: 1px solid #dddddd; cursor: pointer; } .item .active{ background-color: #eeeeee; color: red; font-weight: bold; } .content{ height: 500px; 800px; border: 1px solid #dddddd; margin: 0 auto; } .content .content-content{} </style> </head> <body> <div class="item"> <div class="item-content active">商品介绍</div> <div class="item-content">详细参数</div> <div class="item-content">客户评价</div> </div> <div class="content"> <div class="content-content">内容1</div> <div class="content-content hide">内容2</div> <div class="content-content hide">内容3</div> </div> <script src="jquery-3.3.1.js"></script> <script> // 利用索引实现,代码简洁,但依赖全局唯一的样式item-content content-content,所以注意这二种新式只在这儿使用,且item-content和content-content的内容顺序要对应。 $('.item-content').click(function () { $(this).addClass('active').siblings().removeClass('active'); $('.content-content').eq($(this).index()).removeClass('hide').siblings().addClass('hide'); }); </script> </body> </html>
利用自定义属性实现:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .hide{display:none;} .item{ height: 38px; 800px; border: 1px solid #dddddd; margin: 0 auto; } .item .item-content{ float: left; line-height: 38px; padding: 0 15px; border-right: 1px solid #dddddd; cursor: pointer; } .item .active{ background-color: #eeeeee; color: red; font-weight: bold; } .content{ height: 500px; 800px; border: 1px solid #dddddd; margin: 0 auto; } .content .content-content{} </style> </head> <body> <div class="item"> <div itemId="1" class="item-content active">商品介绍</div> <div itemId="2" class="item-content">详细参数</div> <div itemId="3" class="item-content">客户评价</div> </div> <div class="content"> <div contentId="1" class="content-content">内容1</div> <div contentId="3" class="content-content hide">内容3</div> <div contentId="2" class="content-content hide">内容2</div> </div> <script src="jquery-3.3.1.js"></script> <script> // 利用自定义属性itemId contentId相对应,这样不依赖于顺序,children会用到字符串拼接 $('.item').children().click(function () { $(this).addClass('active').siblings().removeClass('active'); var index = $(this).attr('itemId'); $('.content').children("[contentId="+index+"]").removeClass('hide').siblings().addClass('hide'); }); </script> </body> </html>