如何在javascript中激活标签内容?

时间:2018-05-11 18:02:12

标签: javascript

如何在打开页面时激活London标签内容?

我试图将类设置为“活动”,但它没有帮助。

这是剧本:

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial;}

/* Style the tab */
.tab {
     overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}

 /* Style the buttons inside the tab */
 .tab button {
background-color: inherit;
float: left;
border: none;
outline: none;
cursor: pointer;
padding: 14px 16px;
transition: 0.3s;
font-size: 17px;
}

  /* Change background color of buttons on hover */
.tab button:hover {
   background-color: #ddd;
}

/* Create an active/current tablink class */
 .tab button.active {
background-color: #ccc;
 }

/* Style the tab content */
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
</style>
</head>
<body>

<p>Click on the buttons inside the tabbed menu:</p>

<div class="tab">
  <button class="tablinks active" onclick="openCity(event, 'London')">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>
</div>

<div id="London" class="tabcontent">
 <h3>London</h3>
 <p>London is the capital city of England.</p>
</div>

<div id="Paris" class="tabcontent">
 <h3>Paris</h3>
 <p>Paris is the capital of France.</p> 
</div>

<div id="Tokyo" class="tabcontent">
 <h3>Tokyo</h3>
 <p>Tokyo is the capital of Japan.</p>
</div>

<script>
function openCity(evt, cityName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";

}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(cityName).style.display = "block";
evt.currentTarget.className += " active";
}
 </script>

</body>
</html> 

我从https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_tabs

获得了剧本

由于

2 个答案:

答案 0 :(得分:0)

纯JS解决方案:更改行

evt.currentTarget.className += " active";

document.getElementById(cityName).className += " active";

在脚本的底部(</script>结束标记上方的行)放

openCity(null, 'London');

就是这样。但是你根本不需要使用JS - 请查看@AndrewL answer

答案 1 :(得分:0)

默认情况下,只需手动将display: block添加到London标签,然后让JS在此之后切换显示属性:

<div id="London" class="tabcontent" style="display: block;">

或者,如果您也想使用JS将初始display: block添加到伦敦选项卡,则可以在openCity函数上方添加这两行:

var londonTab = document.getElementById("London");
londonTab.style.display = "block";

jsFiddle: https://jsfiddle.net/AndrewL64/202bou56/