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

html - Toggle CSS hover element with a Javascript button - Stack Overflow

programmeradmin0浏览0评论

Is it possible to use Javascript to toggle an element which changes on hover. I would like to build a button which allows the div to change from the two different states: (1) when the div is not hovered and (2) when the div is hovered.

Any suggestions how this could be done?

Thanks!

TC

Is it possible to use Javascript to toggle an element which changes on hover. I would like to build a button which allows the div to change from the two different states: (1) when the div is not hovered and (2) when the div is hovered.

Any suggestions how this could be done?

Thanks!

TC

Share Improve this question edited Feb 1, 2015 at 16:30 Deduplicator 45.7k7 gold badges72 silver badges123 bronze badges asked Feb 23, 2011 at 1:50 TronCrazeTronCraze 2952 gold badges6 silver badges14 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

It is certainly possible to do this with CSS alone:

div { background-color:#000; }
div:hover { background-color:#cc0000; }

When you hover over the div the background color will turn from black to red.

It is my opinion that using javascript for this task is overkill. You can do some pretty sophisticated things with the :hover pseudo selector. Consider this markup (and CSS):

<div>I'm just a div <h1>I'm just an h1</h1></div>

div h1 { font-size:10px; font-weight:normal; }
div:hover { border:1px dotted #000; }
div:hover h1 { font-size:32px; font-weight:bold; color:#cc0000; }

As you can see, we can use the :hover selector in a rule like above to not only style the hovered element, but any children elements as well. This premise is how a lot of 'fly out' navigation is made with little more than nested uls.

You sure can!

You could do something like:

jQuery:

$("#mydiv").hover(function () 
{
    $(this).toggleClass("active");
    // or $(this).toggle();
  }
);

Standard javascript:

function toggle(obj)
{
    var item = document.getElementById(obj);
    if(item.style.visibility == 'visible') { item.style.visibility = 'hidden'; }
    else { item.style.visibility = 'visible'; }
}

HTML:

<div onmouseover="toggle('mydiv');" onmouseout="toggle('mydiv');" id="mydiv">Hover</div>

<input type = 'button' value = 'change div' onmouseover = 'javascript:getElementById('DivId').className = newStyleClass' onmouseout = 'javascript:getElementById('DivId').className = newStyleClass' />

you can try using jQuery it will make it much easier. $('#divId').css('hover', function(index){ whatever ; });

If you dont prefer that let me know and I can scratch my brain on how to do it in straight js.

发布评论

评论列表(0)

  1. 暂无评论