search
HomeWeb Front-endHTML Tutorial深入理解CSS元素可见性visibility - 小火柴的蓝色理想

前面的话

  visibility属性常见于与display属性的比较中。但实际上,该属性有自己的一些有趣的用途。本文将就visibility属性作详细整理和说明

 

定义

visibility

  值: visible | hidden | collapse | inherit

  初始值: visible

  应用于: 所有元素

  继承性: 有

 

属性

  visible: 元素可见

  hidden:元素不可见,但元素还是会影响文档的布局

  [注意]可以将一个hidden元素的后代元素置为visible,这会使该后代元素正常出现

 collapse:在表格中

或中使用,表示该列或列组的所有单元格不显示。如果用于非表格元素,collapse与hidden含义相同

  [注意]webkit内核浏览器不支持给

或 元素使用collapse属性

 

display

  visibility:hidden与display:none作为隐藏元素的两种方式,常常被人们拿来比较。其实区别很简单,前者不脱离文档流,保留隐藏之前元素占据的物理区域;而后者则脱离文档流,如果重新显示则需要页面的重新绘制。还有一点区别却很少人提到,如果父级设置display:none;子级设置display:block也不会显示;而如果父级设置visibility:hidden;子级设置visibility:visible时子级会显示出来

 

JS

  当元素通过设置visibiliy:hidden之后,虽然还占据物理区域,但已经不可以接受js效果

  //js效果:当鼠标移入元素时,父级的背景颜色变成黑色;移出时背景颜色恢复初始值

 

transition

  其实visibility是离散步骤,在0到1数字范围之内,0表示隐藏,1表示显示。visibility:hidden可以看成visibility:0;visibility:visible可以看成visibility:1。于是,visibility应用transition等同于0~1之间的过渡效果。实际上,只要visibility的值大于0就是显示的。由于这个现象,我们可以利用transition实现元素的延时显示隐藏

<span style="color: #800000;">#oShow</span>{<span style="color: #ff0000;">
    visibility</span>:<span style="color: #0000ff;"> visible</span>;<span style="color: #ff0000;">
    transition</span>:<span style="color: #0000ff;"> visibility 0.2s  0.5s</span>;
}<span style="color: #800000;">
#oShow:hover</span>{<span style="color: #ff0000;">
    visibility</span>:<span style="color: #0000ff;"> hidden</span>;
}

  visibility配合opacity和transtion可以实现真正的元素淡入淡出。如果只用opacity时,即使最后元素opacity变为0,但实现上该图片还是可以覆盖其他元素以及可以接受js效果。所以使用visibility可以实现元素真正的隐藏

<span style="color: #800000;">#oShow</span>{<span style="color: #ff0000;">
    visibility</span>:<span style="color: #0000ff;"> visible</span>;<span style="color: #ff0000;">
    opacity</span>:<span style="color: #0000ff;"> 1</span>;<span style="color: #ff0000;">
    transition</span>:<span style="color: #0000ff;"> 1s</span>;
}<span style="color: #800000;">
#oShow:hover</span>{<span style="color: #ff0000;">
    visibility</span>:<span style="color: #0000ff;"> hidden</span>;<span style="color: #ff0000;">
    opacity</span>:<span style="color: #0000ff;"> 0</span>;
}

 

API

  当前浏览器大部分都是多tab页(多标签页)的模式,但这些页面性能却参差不齐。对于某些性能很差的页面,当用户从其他tab页切换回来时,有可能出现由于页面性能差出现页面错乱、页面卡死甚至浏览器卡死的情况

  HTML5新增了页面可见性API。该API有两个属性,一个事件

  [注意]IE9-和safari浏览器不支持。所以可以通过document.hidden !== 'undefined'来做浏览器的识别

  document.hidden: 表示当前页面是否可见

    当前tab页处于激活态时,document.hidden的属性值是false,否则是true

  document.visibilityState: 返回当前页面的可见状态

<span style="color: #000000;">hidden: 当浏览器最小化、切换tab、电脑锁屏时
visible: 用户正在查看当前页面时
prerender: 文档加载离屏或者不可见
unloaded: 当文档将要被unload时</span>

  [注意]prerender和undloaded不是所有浏览器都支持,用的也不多

  visibilitychange事件: 当document.visibilityState状态变化时触发该事件

应用场景

  [1]当页面属性是hidden时,停止页面中选项卡的定时器或页面中的动画等,减少内存占用

  [2]当通过页面状态的切换,来控制音乐或视频的播放或停止

  [3]...

 

DEMO

【1】页面为非激活页时,暂停页面中的动画;重新激活时,继续动画效果

<span style="color: #800000;">.box</span>{<span style="color: #ff0000;">
    width</span>:<span style="color: #0000ff;"> 500px</span>;<span style="color: #ff0000;">
    background-color</span>:<span style="color: #0000ff;"> lightgreen</span>;<span style="color: #ff0000;">
    border</span>:<span style="color: #0000ff;"> 1px solid black</span>;
}<span style="color: #800000;">
@keyframes loop</span>{<span style="color: #ff0000;">
    0%{
        width</span>:<span style="color: #0000ff;"> 100px</span>;
    }<span style="color: #800000;">
    100%</span>{<span style="color: #ff0000;">
        width</span>:<span style="color: #0000ff;"> 500px</span>;
    }<span style="color: #800000;">
}
#div</span>{<span style="color: #ff0000;">
    width</span>:<span style="color: #0000ff;"> 100px</span>;<span style="color: #ff0000;">
    height</span>:<span style="color: #0000ff;"> 100px</span>;<span style="color: #ff0000;">
    background-color</span>:<span style="color: #0000ff;"> pink</span>;<span style="color: #ff0000;">
    animation</span>:<span style="color: #0000ff;"> loop 200s alternate infinite linear</span>;
}    
<span style="color: #0000ff;"><span style="color: #800000;">div </span><span style="color: #ff0000;">class</span><span style="color: #0000ff;">="box"</span><span style="color: #0000ff;">></span>
    <span style="color: #0000ff;"><span style="color: #800000;">div </span><span style="color: #ff0000;">id</span><span style="color: #0000ff;">="div"</span><span style="color: #0000ff;">></span><span style="color: #800000;">div</span><span style="color: #0000ff;">></span>
<span style="color: #0000ff;"></span><span style="color: #800000;">div</span><span style="color: #0000ff;">></span></span></span>
<span style="color: #0000ff;">function</span><span style="color: #000000;"> getCSS(obj,style){
    </span><span style="color: #0000ff;">if</span><span style="color: #000000;">(window.getComputedStyle){
        </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> getComputedStyle(obj)[style];
    }
    </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> obj.currentStyle[style];
};
</span><span style="color: #0000ff;">var</span> oTimer = setInterval(<span style="color: #0000ff;">function</span><span style="color: #000000;">(){
    document.title</span>=div.innerHTML = parseInt(getCSS(div,'width'<span style="color: #000000;">));
},</span>100<span style="color: #000000;">);
document.addEventListener(</span>'visibilitychange',<span style="color: #0000ff;">function</span><span style="color: #000000;">(){
    </span><span style="color: #0000ff;">if</span><span style="color: #000000;">(document.hidden){
        div.style.animationPlayState </span>= 'paused'<span style="color: #000000;">;
    }</span><span style="color: #0000ff;">else</span><span style="color: #000000;">{
        div.style.animationPlayState </span>= 'running'<span style="color: #000000;">;
    }
    
},</span><span style="color: #0000ff;">false</span>);

【2】页面切换来控制音乐的播放和暂停

<span style="color: #0000ff;"><span style="color: #800000;">audio </span><span style="color: #ff0000;">id</span><span style="color: #0000ff;">="audio"</span><span style="color: #ff0000;"> src</span><span style="color: #0000ff;">="http://7xpdkf.com1.z0.glb.clouddn.com/myocean.mp3"</span><span style="color: #ff0000;"> controls </span><span style="color: #0000ff;">></span><span style="color: #800000;">audio</span><span style="color: #0000ff;">></span></span>
<span style="color: #0000ff;">var</span><span style="color: #000000;"> mark;
document.addEventListener(</span>'visibilitychange',<span style="color: #0000ff;">function</span><span style="color: #000000;">(){
    </span><span style="color: #0000ff;">if</span><span style="color: #000000;">(document.hidden){
        </span><span style="color: #008000;">//</span><span style="color: #008000;">如果用户在切换页面前,自己点了暂停</span>
        <span style="color: #0000ff;">if</span><span style="color: #000000;">(audio.paused){
            mark </span>= <span style="color: #0000ff;">false</span><span style="color: #000000;">;
        }</span><span style="color: #0000ff;">else</span><span style="color: #000000;">{
            audio.pause();
            mark </span>= <span style="color: #0000ff;">true</span><span style="color: #000000;">;
        }    
    }</span><span style="color: #0000ff;">else</span><span style="color: #000000;">{
        </span><span style="color: #008000;">//</span><span style="color: #008000;">当暂停是因为页面切换造成的,则返回当前页面时,继续播放</span>
        <span style="color: #0000ff;">if</span><span style="color: #000000;">(mark){
            audio.play();
        }    
    }
},</span><span style="color: #0000ff;">false</span>);

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between an HTML tag and an HTML attribute?What is the difference between an HTML tag and an HTML attribute?May 14, 2025 am 12:01 AM

HTMLtagsdefinethestructureofawebpage,whileattributesaddfunctionalityanddetails.1)Tagslike,,andoutlinethecontent'splacement.2)Attributessuchassrc,class,andstyleenhancetagsbyspecifyingimagesources,styling,andmore,improvingfunctionalityandappearance.

The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.