简体   繁体   中英

Javascript onClick and onmouseover and onmouseOut

I would like to ask how to differentiate between onClick and onMouseOver and onMouseOut.

For instance, I use onMouseOver to change the tab background to grey using

onMouseOver="this.style.backgroundColor=Blue;"

onMouseOut takes away this background

onMouseOut="this.style.backgroundColor=White;"

How do I write a call for onClick that gives a blue background and keeps it there even when the mouse cursor moves away from the tab?

Thanks

How about you have two CSS classes, "active" and "clicked". They both set the background to blue. On click, you add the "clicked" class. On mouse over, you add the "active" class. On mouse out, you remove the "active" class. If the element had the "clicked" class it'd still have it, and hence keep its color.

You need to work with event listeners. I recommend using a framework for this, like prototypejs or jquery.

You will need event listeners / observers for observing the mouseOver, mouseOut and click events. When your click event fires, you stop observing for mouseOver and mouseOut. This should do the trick.

我会在MouseOut中进行检查,仅在颜色尚未为蓝色时才更改颜色。

Normally I would add a CSS class to the element which has the active (last clicked on item) state. That CSS class can have priority over the normal styling of the element.

I would even use CSS and not JavaScript for hover state changes.

Very simple solution is here for your help. Hope it works for you.

 <script type="text/javascript"> function row_mout(mout_value) { document.getElementById(mout_value).style.background = "#FFFFFF"; } function row_mover(mover_value){ document.getElementById(mover_value).style.background = "#123456"; } function row_click(click_value) { if(document.getElementById('chk_'+click_value).checked == true){ document.getElementById(click_value).style.background = "#123456"; document.getElementById(click_value).onmouseout = ""; document.getElementById(click_value).onmouseover = ""; }//if over else if(document.getElementById('chk_'+click_value).checked == false){ document.getElementById(click_value).style.background = "#FFFFFF"; document.getElementById(click_value).onmouseout = function onmouseout(event){ row_mout(click_value); } document.getElementById(click_value).onmouseover = function onmouseover(event){ row_mover(click_value); } }//else if over } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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