2014-01-17 37 views
0

我正在写javascript,它将在鼠标悬停在其上时更改元素的颜色。我完全知道如何使用jQuery来做到这一点,但这一次我使用使用纯JS或Prototype来做到这一点。使用javascript更改元素onMouseOver的颜色

为什么不这项工作:

<div id="boundary1"></div>

document.getElementById("boundary1").onmouseover(function() { 
    alert("test"); 
}) 

萤火虫返回:

TypeError: document.getElementById(...).onmouseover is not a function

回答

3

你的语法是错误的,你可能会想有点太“jQuery的”,试试这个:

var boundary = document.getElementById('boundary'); 
var mouseOverFunction = function() { 
    // this.style.color = '#000'; // your colour change 
}; 
boundary.onmouseover = mouseOverFunction; 

我分开,以使开发和逻辑清晰的逻辑,它使你的功能可重复使用。

0

尝试:

document.getElementById("boundary1").onmouseover = function() { 
    alert("test"); 
} 

More Info.

+0

有没有诀窍,你是一个bauss – Ortix92

+0

@ Ortix92:请标记为接受的答案,如果它为你工作。 :) –

+0

我还得等上几分钟。有没有办法将选定的元素传递给该函数? – Ortix92

0

使用CSS

<style> 
.changecolour:hover 
{ 
background-color:yellow; 
} 
</style> 

现在你要改变颜色的文字试试这个代码

<td onMouseOver="this.bgColor='#00CC00'" onMouseOut="this.bgColor='#009900'" bgColor=#009900> 
<A HREF="#">Click Here</A></TD> 
1

Prot这种方式可以做到这一点:

$('elementId').observe('mouseenter', function(evt){ 
    this.setStyle('background-color: yellow'); 
}).observe('mouseleave', function(evt){ 
    this.setStyle('background-color: inherit'); 
}); 

但正如其他人已经指出的,真正的方法是用CSS。我可以想象在JS中需要这样做的唯一原因是,如果您必须支持IE < = 8,它不喜欢对除A标记之外的其他任何内容执行:hover伪类。