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

How do I change an onmouseover event using Javascript? - Stack Overflow

programmeradmin4浏览0评论

I have an HTML span which changes it's class onmouseover and onmouseout:

<span id="someSpan" class="static" onmouseover="this.className='active'" onmouseout="this.className='static'">Some Text</span>

I want to be able to enable and disable (change) the onmouseover and onmouseout events using a Javascript function called elsewhere on the page. Is this Possible?

I have an HTML span which changes it's class onmouseover and onmouseout:

<span id="someSpan" class="static" onmouseover="this.className='active'" onmouseout="this.className='static'">Some Text</span>

I want to be able to enable and disable (change) the onmouseover and onmouseout events using a Javascript function called elsewhere on the page. Is this Possible?

Share Improve this question asked Aug 17, 2009 at 13:41 TrastleTrastle 5,1856 gold badges28 silver badges20 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 5

Sure.

document.getElementById('someSpan').onmouseover = 
     function() { 
         this.className='newactive'; 
     };

The safe way is to use a Javascript toolkit like Prototype or JQuery.

They all can do things like this easily but it works cross-browser.

For example, here is how you do it in JQuery.

I would agree jQuery would be easier, but if you would like to stick to JavaScript, I believe this should work:

document.getElementById("elementId").onMouseOut=functionName;

Additionally, jQuery is about 20Kb in size (size of production framework file), so it might slow down the loading of your page. Something to consider if you're just using it for a few things that may be done in JavaScript.

Yes, you can do that simply by assigning to the onmouseover and onmouseout properties of the Element instance for the span, e.g.:

// Define your handler somewhere
function myNewHandler()
{
    // ...new logic...
}

// And where you want to swap it in:
document.getElementById('someSpan').onmouseover = myNewHandler;

...but this is a fairly old-fashioned way to do this. A more modern approach uses addEventListener or attachEvent (depending on whether you're doing standard or IE) to hook up event handlers. Libraries like Prototype, jQuery, and about a dozen others can help.

Code:

document.getElementById("someSpan").onmouseover = function()
{
    //New code
};//Do not forget the semicolon
发布评论

评论列表(0)

  1. 暂无评论