最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

prototypejs - Change color of element onMouseOver using javascript - Stack Overflow

programmeradmin0浏览0评论

I'm writing javascript which will change the color of an element when the mouse hovers over it. I know perfectly how to do this using jQuery, but this time around I have to do it using either pure JS or 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

I'm writing javascript which will change the color of an element when the mouse hovers over it. I know perfectly how to do this using jQuery, but this time around I have to do it using either pure JS or 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

Share Improve this question asked Jan 17, 2014 at 11:33 NickNick 2,9806 gold badges38 silver badges72 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 4

Your syntax is wrong, you may be thinking a little too 'jQuery', try this:

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. 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.

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

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

Now for the text you want to change color

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

Reference : http://www.w3schools./cssref/sel_hover.asp

发布评论

评论列表(0)

  1. 暂无评论