简体   繁体   中英

Show and Hide a DIV with CSS or Javascript?

I just saw a demo that had this jquery code to show and hide a dive on hover, can't this be done with just regualr css though? And if you can do it with css is there any advantage of doing it with javascript?

$('.comment').hover(function() {
  $(this).children('.delete').show();
}, function() {
  $(this).children('.delete').hide();
});

CSS hover works fine with anchor tags, but IE6 does not recognize hover events on things like li tags.

If you were using an anchor tag, however, you could achieve the same effect in CSS:

a.comment       .delete { display: none; }
a.comment:hover .delete { display: block; }

您可以使用CSS执行此操作,但IE6仅支持锚标记(A)上的:hover伪类,因此它不常见。

Jody is correct. Check out the docs for the CSS Display property.

There is more functionality that the .hover will do. If you provide it more than 2 functions it will cycle through all the functions. Example

$('.comment').hover(
    function(){$(this).children('.delete.first').show()},
    function(){$(this).children('.delete.first').hide()},
    function(){$(this).children('.delete.second').show()},
    function(){$(this).children('.delete.second').hide()}
    );

That would show one set of children the first time they hover, then hide, and the next time show a different set of children.

The hover function also works over multiple elements, and only fires if the mouse has left all the elements (not just when it leaves one and moves to another)

I dynamically create something like this on the server side. I'm sure there is a more efficient/prettier way but this usually serves my needs. Basically hides all the divs and un-hides the one that needs to be shown (passed as arg in function from onClick event).

function toggleTab(id)
{
    document.getElementById('divEnrollment').style.display='none';    
    document.getElementById('divSearch').style.display='none';
    document.getElementById('divMeeting').style.display='none';
    document.getElementById('divBenefit').style.display='none';
    document.getElementById('div' + id).style.display='block';

    document.getElementById('spnEnrollment').style.color='blue';    
    document.getElementById('spnSearch').style.color='blue';
    document.getElementById('spnMeeting').style.color='blue';
    document.getElementById('spnBenefit').style.color='blue';
    document.getElementById('spn'+id).style.color = 'red';
}

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