How to define function inside onMouseOver and onMouseOut
<div align="right" style="border:1 #FF0 solid; background-color:#999" onMouseOver="javascript: function(){this.style.backgroundColor = '#DDD';}" onMouseOut="javascript: function(){this.style.backgroundColor = '#999';}">
Register
</div>
开发者_运维知识库When mouseover event triggered it gives this error:
Uncaught SyntaxError: Unexpected token (
What should I do? I want to define a function inside onMouseOver
and onMouseOut
Don't use function
declaration, just do:
onMouseOver = "this.style.backgroundColor = '#DDD';"
And:
onMouseOut = "this.style.backgroundColor = '#999';"
By the way, you should consider unobstrusive javascript.
Why do you want a function in your scenario? You could just use..
onMouseOut="javascript:this.style.backgroundColor = '#999'">
you should take a look at jQuery and using unobtrusive javascript.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
That is all you need, it will pull the jQuery library off of Google.
Then you can have an external stylesheet to handle what you want to do.
<div id="container"> Register </div>
THen you need to create an external stylesheet such as app.css:
#container {border:1 #FF0 solid; background-color:#999;text-align:left;}
And then you can have an external script such as app.js
$('#container').mouseout(function() {
$('#container').css('backgroundColor', '#DDD')
});
Don't forget to link the external css and js to the the page. The external stylesheet needs to be linked to after the jQuery script.
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js
<script src="app.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="app.css">
You can edit the script to add more functions when the mouse does stuff:
$('#container').mouseout($('#container').css('backgroundColor', '#DDD'))
$('#container').mouseover($('#container').css('backgroundColor', '#DDD'))
$('#container').mouseenter($('#container').css('backgroundColor', '#DDD'))
$('#container').mouseup($('#container').css('backgroundColor', '#DDD'))
There is a whole slew of theme here: http://api.jquery.com/category/events/mouse-events/
why don't you just use css?
element:hover(){
}
or is it the js function you need and the bg is just an example?... in this case you can get an easy result with jQuery $("#element").mouseover(function(){ $(this).addClass("bghover"); });
$("#element").mouseoutfunction(){ $(this).removeClass("bghover"); });
You can define external javascript method, which accepts the required argument, and use this method for several elements:
<script language="javascript" type="text/javascript">
function OnMouseDownEventHandler(sender) {
sender.style.backgroundColor = '#DDD';
}
</script>
<div onmousedown="OnMouseDownEventHandler(this);"></div>
精彩评论