jq方法写选项卡的基本原理以及三种方法

使用jq写选项卡,告别了繁琐的循环以及命名规范javascript

基本原理:css

    1.当某一个btn被选中时,将这个btn的背景颜色设为橘色,其他兄弟btn背景颜色设为空(none)html

    2.若是子div与btn的索引相同,就将这个div显示而其余兄弟div隐藏java

      1).css函数参数2的回调函数方法;jquery

      2).原生get方法再转jq对象 再进行设置的方法ide

      3).当前div使用show()方法,其他兄弟div使用hide()方法函数

    关键字:get()  siblings()  show()  hide()  css()this

html页:htm

  4个btn,4个div对象

 <div id="wrap">
        <button>btn1</button>
        <button>btn2</button>
        <button>btn3</button>
        <button>btn4</button>
        <div>1</div>
        <div>2</div>
        <div>3</div>
        <div>4</div>
    </div>

css页:

  大盒子当前无样式,在实际开发中须要指定其宽高;第一个btn背景色为橘黄色;第一个子项div显示,其他兄弟div隐藏

 #wrap div {
            width: 300px;
            height: 200px;
            border: 1px solid red;
            display: none;
        }
        
        #wrap div:nth-of-type(1) {
            display: block;
            /* 第一个子项div显示 */
        }
        
        #wrap button:nth-of-type(1) {
            background: orange;
            /* 第一个btn背景色为橘黄色; */
        }

  

jquery页:

1)首先给btn绑定事件

$("#wrap button").click(function() {
        //当btn被点击后发生的事件
})        

    关键字: click();

2) 当btn被点击时,设置当前选中btn颜色为橘色,而且将其余兄弟btn背景色为空:

$(this).css("background", "orange").siblings("button").css("background", "none")

    关键字:  $(this);  css();   siblings()

3) 声明一个变量,这个变量保存了被选中的btn的下标

var $index = $(this).index();

    关键字:$index; $(this);index();

 // 1:找到全部的子div,而且设置css样式,若是某个div的索引与btn的索引相同,就让他显示
                    $("#wrap div").css("display", function(i) {
                        if (i == $index) {
                            return "block";
                        }
                        return "none";
                    })

 

    关键字:css() ; "display" ; i == $index;

  b:经过get()方法将子div的索引与当前btn的索引绑定,而后再将这个索引转变成jq对象,再使用jq方法将对应div显示

$($("#wrap div").get($(this).index())).css("display", "block").siblings("div").css("display", "none")

    因为get方法是js原生方法,因此应将其转成jq对象才能使用jq方法

    关键字: $()  ; $(this).index; get();css();siblings()    

  c:经过当前btn的索引绑定div的索引,进而将这个索引对应的div显示show(),并将其他的div兄弟元素隐藏hide()

$("#wrap div").eq($(this).index()).show().siblings("div").hide();

    关键字:eq();$(this).index();show();hide()

  这样,就完成了使用jQuery方法实现选项卡。

  以上。

相关文章
相关标签/搜索