Changing visibility property in css?

雨燕双飞 提交于 2019-12-25 08:21:58

问题


<style>
#count2{
visibility:hidden;
}
#count1:hover{
background:#123456;
//how do I change the visibility property of #count2 here?
}
</style>
<div id="count1">My visible element</div>
<div id="count2">My flickering element</div>

My question is clear and might be little weird though. How do I change the visibility property of #count2 to true when somebody hovers on #count1, using only css.


回答1:


Since you're modifying two different elements on hovering one of them, you can use a sibling combinator followed by the #count2 selector in a separate rule for modifying that particular element:

#count2 {
    visibility: hidden;
}

#count1:hover {
    background: #123456;
}

#count1:hover + #count2 {
    visibility: visible;
}



回答2:


You'll have to use the + selector, which selects adjacent siblings:

#count2 {
    visibility:hidden;
}
#count1:hover {
    background:#123456;
}
#count1:hover + #count2 {
    visibility: visible;
}

Here's the fiddle: http://jsfiddle.net/Yyr64/


If you have to target older browsers, and you're using jQuery, this is what you gotta do:

var $count2 = $('#count2');

$('#count1').hover(function(){
    $count2.css('visibility', 'visible');
}, function(){
    $count2.css('visibility', 'hidden');
});

...and here's the fiddle for this: http://jsfiddle.net/Yyr64/1/




回答3:


The above solutions can be abstracted with the following jsfiddle: http://jsfiddle.net/mousepotatoweb/PVHzK/2/

<style>
[id|="count-1"]{
background:#123456;
}

[id|="count-2"]{
visibility:hidden;

}

[id|="count"]:hover ~ [id|="count"] { visibility: visible;}
</style>

<div id="count-1">My visible element</div>
<div id="count-2">My flickering element</div>



回答4:


count2 would need to be a child of count1 in order to do this via css only.

<div id="count1">
    My visible element
    <div id="count2">My flickering element</div>
</div>

#count1:hover #count2{ display: block; background: #ffff00; }
#count2{ display: none; }

When using css2 though, you can use the + selector as in Joseph Silber's answer




回答5:


Use

 display:none;

instead of visibility property.

You can take a look at jquery http://api.jquery.com/show/



来源:https://stackoverflow.com/questions/8094893/changing-visibility-property-in-css

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!