|
| 1 | +<div id="wrapper"> |
| 2 | + <div data-tabname="one">Tab one</div> |
| 3 | + <div data-tabname="two">Tab two</div> |
| 4 | + <div data-tabname="three">Tab three</div> |
| 5 | +</div> |
| 6 | +<script> |
| 7 | + function asTabs(node) { |
| 8 | + var divChildNodes = node.getElementsByTagName('div'); |
| 9 | + Array.prototype.forEach.call(divChildNodes, function(element){ |
| 10 | + var button = document.createElement('button'); |
| 11 | + button.textContent = element.getAttribute('data-tabname'); |
| 12 | + node.insertBefore(button, divChildNodes[0]); |
| 13 | + element.style.display = 'none'; |
| 14 | + }); |
| 15 | + var btnChildNodes = node.getElementsByTagName('button'); |
| 16 | + |
| 17 | + divChildNodes[0].style.display = 'block'; |
| 18 | + btnChildNodes[0].style.backgroundColor = 'red'; |
| 19 | + btnChildNodes[1].style.backgroundColor = 'yellow'; |
| 20 | + btnChildNodes[2].style.backgroundColor = 'yellow'; |
| 21 | + |
| 22 | + addEventListener('click', function(event) { |
| 23 | + if(event.target.nodeName === 'BUTTON') { |
| 24 | + if(event.target.textContent === 'one') { |
| 25 | + divChildNodes[0].style.display = 'block'; |
| 26 | + divChildNodes[1].style.display = 'none'; |
| 27 | + divChildNodes[2].style.display = 'none'; |
| 28 | + btnChildNodes[0].style.backgroundColor = 'red'; |
| 29 | + btnChildNodes[1].style.backgroundColor = 'yellow'; |
| 30 | + btnChildNodes[2].style.backgroundColor = 'yellow'; |
| 31 | + } else if(event.target.textContent === 'two') { |
| 32 | + divChildNodes[1].style.display = 'block'; |
| 33 | + divChildNodes[0].style.display = 'none'; |
| 34 | + divChildNodes[2].style.display = 'none'; |
| 35 | + btnChildNodes[1].style.backgroundColor = 'red'; |
| 36 | + btnChildNodes[0].style.backgroundColor = 'yellow'; |
| 37 | + btnChildNodes[2].style.backgroundColor = 'yellow'; |
| 38 | + } else if(event.target.textContent === 'three') { |
| 39 | + divChildNodes[2].style.display = 'block'; |
| 40 | + divChildNodes[0].style.display = 'none'; |
| 41 | + divChildNodes[1].style.display = 'none'; |
| 42 | + btnChildNodes[2].style.backgroundColor = 'red'; |
| 43 | + btnChildNodes[0].style.backgroundColor = 'yellow'; |
| 44 | + btnChildNodes[1].style.backgroundColor = 'yellow'; |
| 45 | + } |
| 46 | + } |
| 47 | + }); |
| 48 | + } |
| 49 | + asTabs(document.querySelector("#wrapper")); |
| 50 | +</script> |
0 commit comments