效果圖
功能:元素自動切換,當點擊下方小圓點時,控制上方元素同步切換
方法:主要是定義一個全局變量,通過自增變化來控制自動切換效果,其中當自身顯示時,兄弟元素隱藏;給小圓點添加單擊事件,當點擊時,傳遞自身對象給單擊切換函數,通過對象獲取點擊對象的下標值,從而切換元素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>標題</title>
<link rel="stylesheet" href="../css/reset.css">
<script src="./jquery-3.4.1.min.js"></script>
<style type="text/css">
#box{
width: 800px; height: 340px;
margin: 100px auto;
position: relative;
}
.aaa{
width: 800px; height: 300px;
line-height: 300px; text-align: center;
font-size: 100px; color: #fff;
position: absolute; top: 0; left: 0;
}
#div1{
background: red;
z-index: 1;
}
#div2{
background: green;
}
#nav{
width: 100px; height: 20px;
position: absolute; bottom: 0; left: 50%;
margin-left: -50px;
}
#nav p{
width: 20px; height: 20px;
border-radius: 10px;
background: #ccc;
margin: 0 10px;
float: left;
cursor: pointer;
}
#nav .active{
width: 40px;
background: blue;
}
</style>
<script>
$(function(){
// 全局變量
var c = 0;
var aaa = $("#box .aaa");
// 定義自動切換效果
function gunDongBoFang(){
c++; //c = 1
if(c == aaa.length){
c = 0;
};
console.log(c);
// 當自身顯示時,兄弟元素隱藏
aaa.eq(c).show().siblings(".aaa").hide();
// 字符串值無法創建動畫(比如:background-color:red)
$("#nav p").eq(c).animate({width:"40px"}, 500).css({backgroundColor:"blue"})
.siblings("p").css({backgroundColor:"#ccc", width:"20px"});
};
// 定義單擊小圓點切換效果
function danJiBoFang(obj){
// 獲取當前單擊對象的下標值
c = obj.index();
// 當自身顯示時,兄弟元素隱藏
aaa.eq(c).show().siblings(".aaa").hide();
// 字符串值無法創建動畫(比如:background-color:red)
$("#nav p").eq(c).animate({width:"40px"}, 500).css({backgroundColor:"blue"})
.siblings("p").css({backgroundColor:"#ccc", width:"20px"});
};
// 定義單擊小圓點事件
$("#nav p").click(function(){
danJiBoFang($(this));
})
// 定時器,每2秒執行一次
var time = setInterval(gunDongBoFang, 2000);
// 鼠標移入#box元素中,停止定時器
$("#box").mouseenter(function(){
clearInterval(time);
});
// 鼠標移出#box元素後,開始定時器
$("#box").mouseleave(function(){
//鼠標移出時,開始定時器,並將定時器賦值給time變量,而當鼠標再次移入時,則剛好刪除上次的定時器,不會累加
time = setInterval(gunDongBoFang, 2000);
});
});
</script>
</head>
<body>
<div id="box">
<div class="aaa" id="div1">0</div>
<div class="aaa" id="div2">1</div>
<!-- 圖片下方兩個小圓點 -->
<div id="nav">
<p class="active"></p>
<p></p>
</div>
</div>
</body>
</html>