jsノート10のforサイクル練習
3952 ワード
練習する
インターレース変色(css 3実装)
HTML
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
CSS
*{
padding: 0;
margin: 0;
}
.numList{
width: 500px;
margin: 100px auto;
border: 1px solid #ddd;
}
.numList li{
height: 36px;
line-height: 36px;
text-align: center;
font-size: 20px;
list-style: none;
}
/* */
.numList li:nth-child(odd){
background: #00a1d6;
}
/* */
.numList li:nth-child(even){
background: #ffafc9
}
インターレース変色(js実装)
HTML同上
JS
//
var numList = document.getElementsByTagName('li');
for(var i =0;i < numList.length;i++){
if(i%3 === 0){
numList[i].style.background = '#ff0000';
}else if (i%3 === 1) {
numList[i].style.background = '#00ff00';
}else{
numList[i].style.background = '#0000ff';
}
}
タブ
HTML
-
-
-
3
CSS
*{padding: 0;margin: 0;font-family: sans-serif;}
#tabBox{width: 800px;margin: 50px auto;position: relative;}
ul{position: absolute;z-index: 999}
ul:after{display: block;content: "";visibility: hidden;height: 0;clear: both;}
li{width: 100px;height: 36px;line-height: 36px;background: #eee;text-align: center;float: left;list-style: none;margin-right: 12px;border: 1px solid #999; border-bottom: none;cursor: pointer;}
li.active{background: #fff;height: 37px}
#tabBox div{width: 798px;height: 400px;border: 1px solid #999;display: none;position: absolute;top: 37px;}
#tabBox div.active{display: block;line-height: 400px;text-align: center;font-size: 24px;}
JS(方法一)
var tabbox = document.getElementById('tabBox');
var oLi = tabbox.getElementsByTagName('li');
var oDiv = tabbox.getElementsByTagName('div');
function change(index) {
for (var i = 0; i < oLi.length; i++) {
oLi[i].className = "";
oDiv[i].className = "";
}
oLi[index].className = 'active';
oDiv[index].className = 'active';
}
for (var i = 0; i < oLi.length; i++) {
oLi[i].myIndex = i;
oLi[i].onclick = function(){
change(this.myIndex)
}
}
JS(方法二)
for (var i = 0; i < oLi.length; i++) {
~function(i){
oLi[i].onclick = function(){
change(i)
}
}(i)
}
JS(方法三)
for (let i = 0; i < oLi.length; i++) {
oLi[i].onclick = function(){
change(i)
}
}
JS(方法四)
for (var i = 0; i < oLi.length; i++) {
oLi[i].myIndex = i;
oLi[i].onclick = function(index){
for (var j = 0; j < oLi.length; j++) {
oLi[j].className = oDiv[j].className = "";
}
this.className = oDiv[this.myIndex].className = "active"
}
}
JS(方法5)
var tabbox = document.getElementById('tabBox');
var oLi = tabbox.getElementsByTagName('li');
var oDiv = tabbox.getElementsByTagName('div');
// li
var previousIndex = 0;
for (var i = 0; i < oLi.length; i++) {
// li li
oLi[i].currentIndex = i;
oLi[i].onclick = function(){
// li li
if(this.currentIndex === previousIndex){
return;
}
// li
oLi[previousIndex].className = oDiv[previousIndex].className = null;
//
this.className = oDiv[this.currentIndex].className = "active";
// li li
previousIndex = this.currentIndex;
}
}