简体   繁体   English

使用JavaScript更改元素onMouseOver的颜色

[英]Change color of element onMouseOver using javascript

I'm writing javascript which will change the color of an element when the mouse hovers over it. 我正在编写javascript,当鼠标悬停在元素上时,它将更改元素的颜色。 I know perfectly how to do this using jQuery, but this time around I have to do it using either pure JS or Prototype. 我完全知道如何使用jQuery做到这一点,但是这次我必须使用纯JS或Prototype做到这一点。

Why doesn't this work: 为什么这样不起作用:

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

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

firebug returns: 萤火虫返回:

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

Your syntax is wrong, you may be thinking a little too 'jQuery', try this: 您的语法有误,您可能也想过'jQuery',请尝试以下操作:

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

I've separated the logic to make the development and logic clearer, it makes your functions reusable too. 我分离了逻辑以使开发和逻辑更加清晰,这也使您的功能可重复使用。

The Prototype way to do this would be this: 原型的方法是这样的:

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

But as others have already pointed out, the real way to do this is with CSS. 但是正如其他人已经指出的那样,实现此目标的真正方法是使用CSS。 The only reason I could imagine needing to do it in JS is if you have to support IE <= 8, which doesn't like to do the :hover pseudo-class on anything except the A tag. 我可以想象需要在JS中执行此操作的唯一原因是,如果您必须支持IE <= 8,它不喜欢对除A标签之外的任何内容执行:hover伪类。

Try: 尝试:

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

More Info. 更多信息。

Try this code 试试这个代码

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

You can do it using CSS 您可以使用CSS来完成

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

Now for the text you want to change color 现在为您要更改颜色的文本

<span class ="changecolour">Color changes when mouse comes here.</span>

Reference : http://www.w3schools.com/cssref/sel_hover.asp 参考: http : //www.w3schools.com/cssref/sel_hover.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM