Home > Web Front-end > JS Tutorial > body text

How to implement the tab page function using js and jquery respectively

高洛峰
Release: 2016-12-06 14:39:16
Original
1413 people have browsed it

The example in this article describes how js and jquery implement the tab page function respectively. Share it with everyone for your reference, the details are as follows:

First list the styles and html tags

<style type="text/css">
    *{margin: 0;padding: 0;}
    #myul li {list-style: none; float: left; border: 1px solid #ddd; width: 100px; height: 20px; text-align: center; line-height: 20px;}
    #container div{display: none; width: 303px; height: 300px; border: 1px solid #ddd; }
    #container .ssd{display: block;}
    .ssl{background: #abcdef;}
</style>
</head>
<body>
  <div id="tab">
    <ul id="myul">
      <li class="ssl">1</li>
      <li>2</li>
      <li>3</li>
    </ul>
    <div id="container">
      <div class="ssd">woshi1</div>
      <div>woshi2</div>
      <div>woshi3</div>
    </div>
  </div>
</body>
Copy after login

Then the native js code to implement the tab tag

<script type="text/javascript">
var ul = document.getElementById(&#39;myul&#39;);
var li = ul.getElementsByTagName(&#39;li&#39;);
var con = document.getElementById(&#39;container&#39;);
var div = con.getElementsByTagName(&#39;div&#39;);
var len = li.length;
for (var i = 0; i < len; i++) {
li[i].index = i;
li[i].onclick=choose;
li[i].onmouseover = choose;
};
function choose(){
for(var j = 0; j < len; j++) {
    li[j].className = &#39;&#39;;
    div[j].style.display = &#39;none&#39;;
  }
  this.className = &#39;ssl&#39;;
  div[this.index].style.display=&#39;block&#39;;
}
</script>
Copy after login

Then we use jquery to implement the code as follows

$(&#39;#myul li&#39;).click(choose);
$(&#39;#myul li&#39;).hover(choose);
function choose(){
  $(this).addClass(&#39;ssl&#39;).siblings().removeClass(&#39;ssl&#39;);
  $(&#39;#container div&#39;).eq($(this).index()).show().siblings().hide();
}
Copy after login

In fact, the function can be simplified:

function choose(){
  $(this).addClass(&#39;ssl&#39;).siblings().removeClass(&#39;ssl&#39;).parent().next().children().eq($(this).index()).show().siblings().hide();
}
Copy after login


Related labels:
js
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!