简体   繁体   English

如何在加载时激活此JavaScript选项卡?

[英]How do I make this JavaScript tab active on load?

I'm still learning to code and I have a pretty easy/beginner type question. 我仍在学习编码,并且有一个非常简单/入门的类型问题。

When my page loads all tabs in the tab container are grey. 当我的页面加载时,选项卡容器中的所有选项卡均为灰色。 When you click on a tab that tab header takes on the #tab-container ul.tab-menu img.active div settings in the CSS code. 单击选项卡时,选项卡标题将采用CSS代码中的#tab-container ul.tab-menu img.active div设置。 How can I make the first tab take on that active div setting when the page first loads without having to click on it? 当页面首次加载而无需单击时,如何使第一个选项卡采用该活动的div设置?

Here's a fiddle: https://jsfiddle.net/gxswvmb0/1/ 这是一个小提琴: https : //jsfiddle.net/gxswvmb0/1/

The code I tried per first comment: 我在第一个评论中尝试的代码:

$(document).ready(function(){
var activeTabIndex = -1;
var tabNames = ["tab1","tab2","tab3"];

$(".tab-menu > img").click(function(e){
    for(var i=0;i<tabNames.length;i++) {
        if(e.target.id == tabNames[i]) {
            activeTabIndex = i;
        } else {
            $("#"+tabNames[i]).removeClass("active");
            $("#"+tabNames[i]+"-tab").css("display", "none");
        }
    }
    $("#"+tabNames[activeTabIndex]+"-tab").fadeIn();
    $(#tab1).addClass("active");
    return false;
});

}); });

Try to solve the problem by understanding what you are doing. 尝试通过了解自己在做什么来解决问题。 You are binding a function to and event on page load. 您正在将函数绑定到页面加载事件上。 ie when document (DOM) is ready, bind this code to click event on x element. 即,当文档(DOM)准备就绪时, 将此代码绑定到x元素上的click事件。

Once you understand what you are doing, its fairly easy to do what you want. 一旦您了解了自己在做什么,就可以轻松地完成自己想要的事情。 You just need to call the same function on page load with argument as tab1. 您只需要在页面加载时调用相同的函数,其参数为tab1。

hint: $("#tab1").addClass("active"); 提示:$(“#tab1”)。addClass(“ active”);

;) ;)

It's hard to reproduce the page since all of your image assets are not available to me, but I did create a simple demo with what you have provided. 由于您无法使用所有图像资源,因此很难复制页面,但是我确实使用您提供的内容创建了一个简单的演示。 Here: CodePen Demo 此处: CodePen演示
This should be easy to accomplish with CSS. 使用CSS应该很容易做到这一点。 I think you just need to change 我想你只需要改变

#tab-container ul.tab-menu img.active

to

#tab-container ul.tab-menu .active

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM