對于本題修改顏色的不同解法?
window.onload = function(){
? ? ? ? ? ? ? ? ??
? ? ?// 鼠標移動改變背景,可以通過給每行綁定鼠標移上事件和鼠標移除事件來改變所在行背景色。
? ??
? ? ? ? high();
?
}
? ? ?
? ? ?function high(){
? ? ? ? var row=document.getElementsByTagName("tr") ? ;
? ? ? ? for(var i=0;i<row.length;i++){
? ? ? ? ? ? row[i].onmouseover=function(){
? ? ? ? ? ? ? ? this.style.backgroundColor="#f2f2f2";
? ? ? ? ? ? }
? ? ? ? ? ? row[i].onmouseout=function(){
? ? ? ? ? ? ? ? this.style.backgroundColor="#fff";
? ? ? ? ? ? }
? ? ? ? ?}?
? ? }
? ? 這樣的情況下 表格單元行可以變色,但是我不大理解this的用法,還有onclick=del(this)也是不大理解。除開用this還有什么方法嗎?
而且為什么設(shè)置背景顏色用this.setAttribute("style","backgroundColor:red");這種寫法無效呢?
2、function high(){
? ? ? ? var row=document.getElementsByTagName("tr") ? ;
? ? ? ? for(var i=0;i<row.length;i++){
? ? ? ? ? ? row[i].onmouseover=function(){
? ? ? ? ? ? ? ? row[i].style.backgroundColor="#f2f2f2";
? ? ? ? ? ? }
? ? ? ? ? ? row[i].onmouseout=function(){
? ? ? ? ? ? ? ? row[i].style.backgroundColor="#fff";
? ? ? ? ? ? }
? ? ? ? ?}?
? ? }
倘若把代碼改成這樣的話雖然內(nèi)部匿名函數(shù)會執(zhí)行,但是row[i]的顏色卻不會改變。這是為什么呢?
但是我發(fā)現(xiàn)同學(xué)們的代碼
window.onload = function(){
? ? ? ? ? ? ? ? ??
? ? ?// 鼠標移動改變背景,可以通過給每行綁定鼠標移上事件和鼠標移除事件來改變所在行背景色。
? ? ? ? ? ?var x=document.getElementsByTagName("tr");
for(var i=0;i<x.length;i++){
? bgc(x[i]);
}
? ? ?
?
}
function bgc(tr1){
? ? tr1.onmouseover=function(){
? ? ? ? tr1.style.backgroundColor="#f2f2f2";
? ? }
? ? tr1.onmouseout=function(){
? ? ? ? tr1.style.backgroundColor="#fff";
? ? }
}
這樣傳參卻是有用的? ?for循環(huán)所處的位置不一樣為什么結(jié)果就不一樣?
3、繼續(xù)改變代碼
function high(){
? ? ? ? var row=document.getElementsByTagName("tr") ? ;
? ? ? ? for(var i=0;i<row.length;i++){
? ? ? ? ? ? a=row[i];
? ? ? ? ? ? a.onmouseover=function(){
? ? ? ? ? ? ? ? a.style.backgroundColor="#f2f2f2";
? ? ? ? ? ? }
? ? ? ? ? ? a.onmouseout=function(){
? ? ? ? ? ? ? ? a.setAttribute("style","backgroundColor:red");
? ? ? ? ? ? }
? ? ? ? ?}?
? ? }
這樣的話 只有最后一行才能改變顏色而上面幾行卻無動于衷是為什么?
2018-03-28
一個css樣式就能變色