2013-12-16 24 views
0

我想在少數div上做一個背景更改,但我不知道如何。如何在兩個以上的div元素上調用javascript函數?

這裏是腳本:

<script>  
function hatterCsere() 
{ 
    var x=document.getElementById("aktualis"); 
    x.style.backgroundColor="#666"; 
    x.style.color="#ffffff"; 
}; 

function hatterCserevisza(a) 
{ 
    var y=document.getElementById("aktualis"); 
    y.style.backgroundColor="#CCC"; 
    y.style.color="#000000";  
}; 
</script> 

,這裏是正文:

<div class=aktualis id="aktualis" onMouseover="hatterCserevisza();" onMouseout="hatterCsere()"> 
    <p>Garabonciás Karácsony</p> 
</div> 
<div class=aktualis id="tanar"> 
    <p>Új Tanár Érkezett</p> 
</div> 

而且我想使用的 「tanar」 分區的功能。

+3

你應該使用jQuery;它使這種事情更容易。 –

+9

否;你應該使用CSS和':hover'選擇器。 – SLaks

+2

將您想要更改的div作爲參數傳遞給您的函數,而不是對id'aktualis'進行硬編碼。 –

回答

0

使用函數參數。放置參數來指定元素。然後你可以交叉元素地完成它。 例子:

function hatterCsere(element) 
{ 
    var x=element; 
    x.style.backgroundColor="#666"; 
    x.style.color="#ffffff"; 
}; 

function hatterCserevisza(element) 
{ 
    var y=element; 
    y.style.backgroundColor="#CCC"; 
    y.style.color="#000000"; 
}; 

你可以這樣調用:

 <div class=aktualis id="aktualis" onmouseover="hatterCserevisza(this);" onmouseout="hatterCsere(this)"> 
     <p>Garabonciás Karácsony</p> 
    </div> 
    <div class=aktualis id="tanar" onmouseover="hatterCserevisza(this);" onmouseout="hatterCsere(this)"> 
     <p>Új Tanár Érkezett</p> 
    </div> 
2

在JavaScript中你不應該這樣做,你應該這樣做在CSS中,像這樣的:

.aktualis:hover{ 
    background-color:red; /*or whatever you want it to be */ 
} 

但是,如果你需要使用JavaScript,

如果每個div有類名`aktualis',你可以這樣做

var elements=document.getElementsByClassName("aktualis"); 
for(var i=0;i<elements.length;i++){ 
    func_to_call(elements[i]); 
} 
+1

我對*純粹*爲CSS方法upvoting; JavaScript不是必需的。 –

0

同意與第二(SLaks的)評論你會得到

<!DOCTYPE html > 
<html> 
    <head> 
    <title> Bla! </title> 
    <style type='text/css'> 
     div.bla { color:green;background-color:red; } 
     div.bla:hover { color:red;background-color:green; } 
    </style> 
    <script type='text/javascript'> 
    </script> 
    </head> 
    <body> 
     <div class='bla'>div 1</div> 
     <div class='bla'>div 2</div> 
    </body> 
</html> 
+0

謝謝,使用完整答案, 但這是我的作業。但現在我看到我的作業標題是: 「如何使用javascript unsesery」 –

0

試試這個:

function hatterCsere(id) 
{ 

var x=document.getElementById(id); 
x.style.backgroundColor="#666"; 
x.style.color="#ffffff"; 
} 

function hatterCserevisza(id) 
{ 

var y=document.getElementById(id); 
y.style.backgroundColor="#CCC"; 
y.style.color="#000000"; 

} 

<div class='aktualis' id="aktualis" onMouseover="hatterCserevisza(this.id);" onMouseout="hatterCsere(this.id)"> 
      <p>Garabonciás Karácsony</p> 
     </div> 
     <div class='aktualis' id="tanar" onMouseover="hatterCserevisza(this.id);" onMouseout="hatterCsere(this.id)"> 
      <p>Új Tanár Érkezett</p> 
     </div> 
相關問題