基于jQuery实现自动或点击切换效果

    技术2022-07-11  79

    效果图

    功能:元素自动切换,当点击下方小圆点时,控制上方元素同步切换

    方法:主要是定义一个全局变量,通过自增变化来控制自动切换效果,其中当自身显示时,兄弟元素隐藏;给小圆点添加单击事件,当点击时,传递自身对象给单击切换函数,通过对象获取点击对象的下标值,从而切换元素

    <!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>
    Processed: 0.018, SQL: 9