js 两个方法构建n*n的格子(n从输入框填写),鼠标放上去背景变成红色,移除恢复正常 鼠标点击格子背景固定为蓝色,鼠标hover时也不变红,再次点击恢复正常 格子大小可用css控制,默认背景色都是
方法一:
var num = document.getElementById("num");
var btn = document.getElementById("btn");btn.onclick = function(){var n = num.value;for(var i = 0;i < n;i++){for(var j = 0;j < n;j++){var div = document.createElement("div");document.body.appendChild(div);div.style.borderWidth = "1px";div.style.borderColor = "#000";div.style.borderStyle = "solid";div.style.width = "80px";div.style.height = "80px";div.style.display = "inline-block";div.flag = true; //让每个创建的div都携带一个自定义的变量// div.onclick = function(e){// e.stopPropagation();// this.style.backgroundColor = "blue";// }div.addEventListener("click",function(){console.log(this.flag)if(this.flag){this.style.backgroundColor = "blue";}else {this.style.backgroundColor = "white";}this.flag = !this.flag;})div.addEventListener("mouseover",turn1)function turn1(){if(this.flag){this.style.backgroundColor = "red";}else {this.style.backgroundColor = "blue";}}div.addEventListener("mouseout",turn2)function turn2(){if(this.flag){this.style.backgroundColor = "white";}else {this.style.backgroundColor = "blue";}}}document.write("
");}
}
方法二:(标签携带数据法)
var item = document.getElementById("item");
var btn = document.getElementById("btn");btn.onclick = function(){var n = item.value;for(var i = 0;i < n;i++){for(var j = 0;j < n;j++){var div = document.createElement("div");document.body.appendChild(div);div.style.borderWidth = "1px";div.style.borderStyle = "solid";div.style.borderColor = "#000";div.style.display = "inline-block";div.style.width = "80px";div.style.height = "80px";div.dataset.flag = 0;div.onclick = function(){console.log(this.dataset.flag)if(this.dataset.flag % 2 == 0){this.style.backgroundColor = "blue";}else {this.style.backgroundColor = "#fff";console.log(1)}this.dataset.flag ++;}div.onmouseover = function(){if(this.dataset.flag % 2 == 0){this.style.backgroundColor = "red";}else {this.style.backgroundColor = "blue";}}div.onmouseout = function(){if(this.dataset.flag % 2 == 0){this.style.backgroundColor = "#fff";}else {this.style.backgroundColor = "blue";}}}var bdiv = docment.creatElement("div");document.body.appendChild(bdiv); //每次循环5个之后再后面插入一个div使其换行}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
