Содержание
- 1 Overlay Another Element
- 2 transform
- 3 Hide Scrollbars But Keep Functionality
- 4 Usage
- 5 Прием Clearfix
- 6 More
- 7 CSS Reference
- 8 CSS Properties
- 9 Images
- 10 Yes, sort of..
- 11 Property Values
- 12 Miscellaneous
- 13 Images
- 14 Решение проблемы
- 15 JavaScript
- 16 opacity and filter: opacity()
- 17 More Examples
- 18 WebKit
- 19 Hiding content with content-visibility: hidden #
- 20 Skipping rendering work with content-visibility #
- 21 Mozilla
- 22 clip-path
- 23 Absolute position
- 24 Setting Page and Post Visibility # Setting Page and Post Visibility
- 25 Low-level API
- 26 ЕЩЁ
Overlay Another Element
An element can be visually hidden by positioning another over the top which has the same color as the background. In this example, an pseudo-element is overlaid, although any child element could be used:
See the Pen hide with an overlay by SitePoint (@SitePoint) on CodePen.
While technically possible, this option required more code than other options.
metric | effect |
---|---|
browser support | excellent |
accessibility | content still read |
layout affected? | no, if absolutely positioned |
rendering required | paint |
performance | reasonable if careful |
animation frames possible? | yes |
events triggered when hidden? | yes, when a pseudo or child element is overlaid |
transform
The property can be used to translate (move), scale, rotate, or skew an element. A or off-screen will hide the element:
See the Pen hide with transform: scale(0); by SitePoint (@SitePoint) on CodePen.
offers excellent performance and hardware acceleration because the element is effectively moved into a separate layer and can be animated in 2D or 3D. The original layout space remains as is, but no events will be triggered by a fully hidden element.
metric | effect |
---|---|
browser support | good |
accessibility | content still read |
layout affected? | no — the original dimensions remain |
rendering required | composition |
performance | best, can use hardware acceleration |
animation frames possible? | yes |
events triggered when hidden? | no |
Hide Scrollbars But Keep Functionality
To hide the scrollbars, but still be able to keep scrolling, you can use the following code:
Example
/* Hide scrollbar for Chrome, Safari and Opera */ .example::-webkit-scrollbar { display: none;}/* Hide scrollbar for IE, Edge and Firefox */.example { -ms-overflow-style: none; /* IE and Edge */ scrollbar-width: none; /* Firefox */}
Webkit browsers, such as Chrome, Safari and Opera, supports the non-standard pseudo element, which allows us to modify the look of the browser’s scrollbar. IE and Edge supports the property, and Firefox supports the property, which allows us to hide the scrollbar, but keep functionality.
Usage
...<scriptsrc="/node_modules/focus-visible/dist/focus-visible.min.js"></script></body></html>
We suggest that users selectively disable the default focus style by selecting for the case when the polyfill is loaded and is not applied to the element:
.js-focus-visiblefocusnot(.focus-visible){outlinenone;}
If there are elements which should always have a focus ring shown, authors may explicitly add the class. If explicitly added, it will not be removed on .
.js-focus-visiblefocusnot(data-focus-visible-added]){outlinenone;}
The script uses two heuristics to determine whether the keyboard is being (or will be) used:
-
a event immediately following a event where the key pressed was either , , or an arrow key.
-
focus moves into an element which requires keyboard interaction, such as a text field
NOTE: this means that HTML elements like or will always match the :focus-visible selector, regardless of whether they are focused via a keyboard or a mouse.
-
TODO: ideally, we also trigger keyboard modality following a keyboard event which activates an element or causes a mutation; this still needs to be implemented.
<scriptsrc="https://cdn.polyfill.io/v2/polyfill.min.js?features=Element.prototype.classList"><script>
It could be very expensive to apply this polyfill automatically to every shadow root that is created in a given document, so the polyfill ignores shadow roots by default. If you are using Shadow DOM in a component, it is possible to apply this polyfill imperatively to the component’s shadow root:
if(window.applyFocusVisiblePolyfill!=null){window.applyFocusVisiblePolyfill(myComponent.shadowRoot);}
When this polyfill is lazy-loaded, and you are applying the polyfill to a shadow root with JavaScript, it is important to know when the polyfill has become available before trying to use it.
In order to act at the right time, you can observe the global event:
window.addEventListener('focus-visible-polyfill-ready',()=>window.applyFocusVisiblePolyfill(myComponent.shadowRoot),{ oncetrue});
Important: this event is only intended to support late application of the polyfill in lazy-loading use cases. Do not write code that depends on the event firing, as it is timing dependent and only fired once. If you plan to lazy-load the polyfill, it is recommended that you check for it synchronously (see example above under «Shadow DOM») and listen for the event only if the polyfill isn’t available yet.
Until all browsers ship developers will need to use it defensively to avoid accidentally removing focus styles in legacy browsers. This is easy to do with the polyfill.
.js-focus-visiblefocusnot(.focus-visible){outlinenone;}.js-focus-visible.focus-visible{ …}
buttonfocus{ …}buttonfocusnot(focus-visible){ …}buttonfocus-visible { …}
In the future, when all browsers support , the snippets above will be unnecessary. But until that time it’s important to be mindful when you use and to ensure you always have a fallback strategy.
Прием Clearfix
При помощи этого метода мы используем CSS для добавления содержимого после нашего контейнера div. Это созданное содержимое затем перекроет наш div, таким образом заставив его вмещать дочерние элементы. После этого, очевидно, нам не нужно видеть его содержимое, так что мы должны быть уверены, что спрятали его от просмотра.
Вернитесь в свою таблицу стилей, удалите «overflow: hidden;» из контейнера div, а затем добавьте следующее:
CSS
#container { … other styles _height: 1%; }
#container:after { content: «.»; visibility: hidden; display: block; clear: both; height: 0; font-size: 0; }
1 2 3 4 5 6 7 8 9 10 11 |
#container { …otherstyles _height1%;} #container:after { content».»; visibilityhidden; displayblock; clearboth; height; font-size;} |
Может показаться на первый взгляд сложно, но уверяю вас, что это довольно просто.
_height: Приводит в действие «haslayout» в Internet Explorer’е, используя прием с символом подчеркивания, непосредственно для IE6.
content: После контейнера div добавляем точку.
visibility: Нам не нужно видеть точку, поэтому убираем ее со страницы. (Эквивалентно настройке непрозрачности: 0;)
display: Заставляем точку отображаться на уровне блока, вместо заданного первоначально уровня строки (inline).
clear: Важнейшее свойство. Перекрывает основной и боковой div’ы. То же самое, что добавление несемантического <div style=»clear: both;»> к нашей странице.
height: Не занимаем никакого места.
font-size: Мера предосторожности для Firefox. Этот браузер иногда добавляет чуть-чуть пространства после нашего родительского элемента
Лечится установкой размера шрифта в ноль.
More
Fullscreen VideoModal BoxesDelete ModalTimelineScroll IndicatorProgress BarsSkill BarRange SlidersTooltipsDisplay Element HoverPopupsCollapsibleCalendarHTML IncludesTo Do ListLoadersStar RatingUser RatingOverlay EffectContact ChipsCardsFlip CardProfile CardProduct CardAlertsCalloutNotesLabelsCirclesStyle HRCouponList GroupList Without BulletsResponsive TextCutout TextGlowing TextFixed FooterSticky ElementEqual HeightClearfixResponsive FloatsSnackbarFullscreen WindowScroll DrawingSmooth ScrollGradient Bg ScrollSticky HeaderShrink Header on ScrollPricing TableParallaxAspect RatioResponsive IframesToggle Like/DislikeToggle Hide/ShowToggle Dark ModeToggle TextToggle ClassAdd ClassRemove ClassActive ClassTree ViewRemove PropertyOffline DetectionFind Hidden ElementRedirect WebpageZoom HoverFlip BoxCenter VerticallyCenter Button in DIVTransition on HoverArrowsShapesDownload LinkFull Height ElementBrowser WindowCustom ScrollbarHide ScrollbarDevice LookContenteditable BorderPlaceholder ColorText Selection ColorBullet ColorVertical LineDividersAnimate IconsCountdown TimerTypewriterComing Soon PageChat MessagesPopup Chat WindowSplit ScreenTestimonialsSection CounterQuotes SlideshowClosable List ItemsTypical Device BreakpointsDraggable HTML ElementJS Media QueriesSyntax HighlighterJS AnimationsGet Iframe Elements
CSS Reference
CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS AnimatableCSS UnitsCSS PX-EM ConverterCSS ColorsCSS Color ValuesCSS Default ValuesCSS Entities
CSS Properties
align-content align-items align-self all animation animation-delay animation-direction animation-duration animation-fill-mode animation-iteration-count animation-name animation-play-state animation-timing-function
backface-visibility background background-attachment background-blend-mode background-clip background-color background-image background-origin background-position background-repeat background-size border border-bottom border-bottom-color border-bottom-left-radius border-bottom-right-radius border-bottom-style border-bottom-width border-collapse border-color border-image border-image-outset border-image-repeat border-image-slice border-image-source border-image-width border-left border-left-color border-left-style border-left-width border-radius border-right border-right-color border-right-style border-right-width border-spacing border-style border-top border-top-color border-top-left-radius border-top-right-radius border-top-style border-top-width border-width bottom box-decoration-break box-shadow box-sizing break-after break-before break-inside
caption-side caret-color @charset clear clip clip-path color column-count column-fill column-gap column-rule column-rule-color column-rule-style column-rule-width column-span column-width columns content counter-increment counter-reset cursor
direction display empty-cells filter flex flex-basis flex-direction flex-flow flex-grow flex-shrink flex-wrap float font @font-face font-family font-feature-settings font-kerning font-size font-size-adjust font-stretch font-style font-variant font-variant-caps font-weight
grid grid-area grid-auto-columns grid-auto-flow grid-auto-rows grid-column grid-column-end grid-column-gap grid-column-start grid-gap grid-row grid-row-end grid-row-gap grid-row-start grid-template grid-template-areas grid-template-columns grid-template-rows
hanging-punctuation height hyphens @import isolation justify-content @keyframes left letter-spacing
line-height list-style list-style-image list-style-position list-style-type
margin margin-bottom margin-left margin-right margin-top max-height max-width @media min-height min-width mix-blend-mode
object-fit object-position opacity order outline outline-color outline-offset outline-style outline-width overflow overflow-x overflow-y
padding padding-bottom padding-left padding-right padding-top page-break-after page-break-before page-break-inside perspective perspective-origin pointer-events position quotes
resize right
scroll-behavior
tab-size table-layout text-align text-align-last text-decoration text-decoration-color text-decoration-line text-decoration-style text-indent text-justify text-overflow text-shadow text-transform top
transform transform-origin transform-style transition transition-delay transition-duration transition-property transition-timing-function
unicode-bidi user-select
vertical-align visibility
white-space width word-break word-spacing word-wrap writing-mode
z-index
Images
SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider
Yes, sort of..
When you ask the question, «Can the scroll-bars of a browser be removed in some way, rather than simply hidden or camouflaged», everyone will say «Not possible» because it is not possible to remove the scrollbars from all browsers in a compliant and cross-compatible way, and then there’s the whole argument of usability.
However, it is possible to prevent the browser from ever having the need to generate and display scrollbars if you do not allow your webpage to overflow.
This just means that we have to proactively substitute the same behavior that the browser would typically do for us and tell the browser thanks but no thanks buddy. Rather than try to remove scrollbars (which we all know is not possible) we can avoid scrolling (perfectly feasible) and scroll within the elements that we make and have more control over.
Create a div with overflow hidden. Detect when the user attempts to scroll, but is unable to because we’ve disabled the browsers ability to scroll with overflow: hidden.. and instead move the content up using JavaScript when this occurs. Thereby creating our own scrolling without the browsers default scrolling or use a plugin like iScroll.
Property Values
Value | Description | Play it |
---|---|---|
visible | Default value. The element is visible | Play it » |
hidden | The element is hidden (but still takes up space) | Play it » |
collapse | Only for table rows (<tr>), row groups (<tbody>), columns (<col>),
column groups (<colgroup>). This value removes a row or column,
but it does not affect the table layout. The space taken up by the row or column
will be available for other content. If collapse is used on other elements, it renders as «hidden» |
Play it » |
initial | Sets this property to its default value. Read about initial | Play it » |
inherit | Inherits this property from its parent element. Read about inherit |
Miscellaneous
. Though this element does not appear in the latest revision.
The BarProp object is a child of the object and represents the user interface element that contains a scrolling mechanism, or some similar interface concept. will return if the scroll bars are visible.
The History API also includes features for scroll restoration on page navigation to persist the scroll position on page load.
can be used to check the status of scrollrestoration or change its status (appending . Auto is the default value. Changing it to manual means that you as the developer will take ownership of any scroll changes that may be required when a user traverses the app’s history. If you need to, you can keep track of the scroll position as you push history entries with history.pushState().
Images
SlideshowSlideshow GalleryModal ImagesLightboxResponsive Image GridImage GridTab GalleryImage Overlay FadeImage Overlay SlideImage Overlay ZoomImage Overlay TitleImage Overlay IconImage EffectsBlack and White ImageImage TextImage Text BlocksTransparent Image TextFull Page ImageForm on ImageHero ImageBlur Background ImageChange Bg on ScrollSide-by-Side ImagesRounded ImagesAvatar ImagesResponsive ImagesCenter ImagesThumbnailsBorder Around ImageMeet the TeamSticky ImageFlip an ImageShake an ImagePortfolio GalleryPortfolio with FilteringImage ZoomImage Magnifier GlassImage Comparison Slider
Решение проблемы
Когда вы делаете плавающими все дочерние элементы, родитель, по существу, не занимает никакого места. Чтобы нагляднее продемонстрировать этот факт, давайте зададим контейнеру произвольную высоту 50px, а затем уменьшим непрозрачность дочерних div’ов настолько, чтобы увидеть внизу красный фон.
CSS
#container { .. other styles height: 50px; }
#main, #sidebar { opacity: .5; }
1 2 3 4 5 6 |
#container { ..otherstyles height50px;} #main, #sidebar { opacity.5;} |
Обновите ваш браузер и вы увидите:
Странно. Мы указали высоту 50px для нашего контейнера div, однако основной (main) и боковой (sidebar ) div’ы явно переполняют границы родителя (container), выглядят неправильно и ведут себя как хотят.
CSS
#container { …other styles overflow: hidden; }
1 2 3 4 |
#container { …otherstyles overflowhidden; } |
После следующего обновления мы увидим:
Ну, это нам частично помогло. Теперь уже не нужно беспокоиться о дочерних элементах, не слушающихся своего родителя. Но на самом деле это не так уж помогло решить нашу проблему.
«Старайтесь, как только возможно избежать установки высоты. Есть более умный метод».
Решение – убрать свойство высоты контейнера. Удалите следующее свойство.
CSS
#container { …other styles height: 50px; /* Remove this */ }
1 2 3 4 |
#container { …otherstyles height50px;/* Remove this */ } |
Последнее обновление и, похоже, наша проблема решена.
Вы также можете удалить свойства непрозрачности. Они были нужны только в целях наглядности.
JavaScript
JS Array concat() constructor copyWithin() entries() every() fill() filter() find() findIndex() forEach() from() includes() indexOf() isArray() join() keys() length lastIndexOf() map() pop() prototype push() reduce() reduceRight() reverse() shift() slice() some() sort() splice() toString() unshift() valueOf()
JS Boolean constructor prototype toString() valueOf()
JS Classes constructor() extends static super
JS Date constructor getDate() getDay() getFullYear() getHours() getMilliseconds() getMinutes() getMonth() getSeconds() getTime() getTimezoneOffset() getUTCDate() getUTCDay() getUTCFullYear() getUTCHours() getUTCMilliseconds() getUTCMinutes() getUTCMonth() getUTCSeconds() now() parse() prototype setDate() setFullYear() setHours() setMilliseconds() setMinutes() setMonth() setSeconds() setTime() setUTCDate() setUTCFullYear() setUTCHours() setUTCMilliseconds() setUTCMinutes() setUTCMonth() setUTCSeconds() toDateString() toISOString() toJSON() toLocaleDateString() toLocaleTimeString() toLocaleString() toString() toTimeString() toUTCString() UTC() valueOf()
JS Error name message
JS Global decodeURI() decodeURIComponent() encodeURI() encodeURIComponent() escape() eval() Infinity isFinite() isNaN() NaN Number() parseFloat() parseInt() String() undefined unescape()
JS JSON parse() stringify()
JS Math abs() acos() acosh() asin() asinh() atan() atan2() atanh() cbrt() ceil() cos() cosh() E exp() floor() LN2 LN10 log() LOG2E LOG10E max() min() PI pow() random() round() sin() sqrt() SQRT1_2 SQRT2 tan() tanh() trunc()
JS Number constructor isFinite() isInteger() isNaN() isSafeInteger() MAX_VALUE MIN_VALUE NEGATIVE_INFINITY NaN POSITIVE_INFINITY prototype toExponential() toFixed() toLocaleString() toPrecision() toString() valueOf()
JS OperatorsJS RegExp constructor compile() exec() g global i ignoreCase lastIndex m multiline n+ n* n? n{X} n{X,Y} n{X,} n$ ^n ?=n ?!n source test() toString() (x|y) . \w \W \d \D \s \S \b \B \0 \n \f \r \t \v \xxx \xdd \uxxxx
JS Statements break class continue debugger do…while for for…in for…of function if…else return switch throw try…catch var while
JS String charAt() charCodeAt() concat() constructor endsWith() fromCharCode() includes() indexOf() lastIndexOf() length localeCompare() match() prototype repeat() replace() search() slice() split() startsWith() substr() substring() toLocaleLowerCase() toLocaleUpperCase() toLowerCase() toString() toUpperCase() trim() valueOf()
opacity and filter: opacity()
The and properties can be passed a number between 0 and 1, or a percentage between 0% and 100% denoting fully transparent and fully opaque accordingly.
See the Pen hide with opacity: 0 by SitePoint (@SitePoint) on CodePen.
There’s little practical difference between the two in modern browsers, although should be used if multiple effects are applied at the same time (blur, contrast, grayscale etc.)
Opacity can be animated and offers great performance, but be wary that a fully transparent element remains on the page and can trigger events.
metric | effect |
---|---|
browser support | good, but IE only supports 0 to 1 |
accessibility | content not read if 0 or 0% is set |
layout affected? | no |
rendering required | composition |
performance | best, can use hardware acceleration |
animation frames possible? | yes |
events triggered when hidden? | yes |
More Examples
Difference between the display property and the visibility property:
function demoDisplay() { document.getElementById(«myP1»).style.display = «none»; }function demoVisibility() { document.getElementById(«myP2»).style.visibility = «hidden»; }
Toggle between hiding and showing an element:
function myFunction() { var x = document.getElementById(‘myDIV’); if (x.style.visibility === ‘hidden’) { x.style.visibility = ‘visible’; } else { x.style.visibility = ‘hidden’; }}
Hide and show an <img> element:
function hideElem() { document.getElementById(«myImg»).style.visibility = «hidden»; }function showElem() { document.getElementById(«myImg»).style.visibility = «visible»; }
WebKit
WebKit extensions related to scroll-bar customization are:
These can each be combined with additional pseudo-selectors:
- – The horizontal pseudo-class applies to any scrollbar pieces that have a horizontal orientation.
- – The vertical pseudo-class applies to any scrollbar pieces that have a vertical orientation.
- – The decrement pseudo-class applies to buttons and track pieces. It indicates whether or not the button or track piece will decrement the view’s position when used (e.g., up on a vertical scrollbar, left on a horizontal scrollbar).
- – The increment pseudo-class applies to buttons and track pieces. It indicates whether or not a button or track piece will increment the view’s position when used (e.g., down on a vertical scrollbar, right on a horizontal scrollbar).
- – The start pseudo-class applies to buttons and track pieces. It indicates whether the object is placed before the thumb.
- – The end pseudo-class applies to buttons and track pieces. It indicates whether the object is placed after the thumb.
- – The double-button pseudo-class applies to buttons and track pieces. It is used to detect whether a button is part of a pair of buttons that are together at the same end of a scrollbar. For track pieces it indicates whether the track piece abuts a pair of buttons.
- – The single-button pseudo-class applies to buttons and track pieces. It is used to detect whether a button is by itself at the end of a scrollbar. For track pieces it indicates whether the track piece abuts a singleton button.
- – Applies to track pieces and indicates whether or not the track piece runs to the edge of the scrollbar, i.e., there is no button at that end of the track.
- – Applies to all scrollbar pieces and indicates whether or not a scrollbar corner is present.
- – Applies to all scrollbar pieces and indicates whether or not the window containing the scrollbar is currently active. (In recent nightlies, this pseudo-class now applies to ::selection as well. We plan to extend it to work with any content and to propose it as a new standard pseudo-class.)
Examples of these combinations
Styling Scrollbars — Webkit.org
What if you want to keep the content unrendered regardless of whether or not it is on-screen, while leveraging the benefits of cached rendering state? Enter: .
The property gives you all of the same benefits of unrendered content and cached rendering state as does off-screen. However, unlike with , it does not automatically start to render on-screen.
This gives you more control, allowing you to hide an element’s contents and later unhide them quickly.
Compare it to other common ways of hiding element’s contents:
- : hides the element and destroys its rendering state. This means unhiding the element is as expensive as rendering a new element with the same contents.
- : hides the element and keeps its rendering state. This doesn’t truly remove the element from the document, as it (and it’s subtree) still takes up geometric space on the page and can still be clicked on. It also updates the rendering state any time it is needed even when hidden.
, on the other hand, hides the element while preserving its rendering state, so, if there are any changes that need to happen, they only happen when the element is shown again (i.e. the property is removed).
Some great use cases for are when implementing advanced virtual scrollers, and measuring layout.
Skipping rendering work with content-visibility #
It may be hard to figure out which containment values to use, since browser optimizations may only kick in when an appropriate set is specified. You can play around with the values to see what works best, or you can use another CSS property called to apply the needed containment automatically. ensures that you get the largest performance gains the browser can provide with minimal effort from you as a developer.
The content-visibility property accepts several values, but is the one that provides immediate performance improvements. An element that has gains , and containment. If the element is off-screen (and not otherwise relevant to the user—relevant elements would be the ones that have focus or selection in their subtree), it also gains containment (and it stops
and
its contents).
What does this mean? In short, if the element is off-screen its descendants are not rendered. The browser determines the size of the element without considering any of its contents, and it stops there. Most of the rendering, such as styling and layout of the element’s subtree are skipped.
As the element approaches the viewport, the browser no longer adds the containment and starts painting and hit-testing the element’s content. This enables the rendering work to be done just in time to be seen by the user.
Mozilla
Mozilla does have some extensions for manipulating the scroll-bars, but they are all recommended not to be used.
- They recommend using overflow:hidden in place of this.
- Similar to overflow-x
- Similar to overflow-y
Only works internally within a users profile settings. Disables scrolling XML root elements and disables using arrow keys and mouse wheel to scroll web pages.
Further details about Mozilla
This is not really useful as far as I know, but it’s worth noting that the attribute which controls whether or not scrollbars are displayed in Firefox is (reference link):
- Attribute: scrollbars
- Type: nsIDOMBarProp
- Description: The object that controls whether or not scrollbars are shown in the window. This attribute is «replaceable» in JavaScript. Read only
clip-path
The property creates a clipping region that determines which parts of an element are visible. Using a value such as will completely hide the element.
See the Pen hide with clip-path by SitePoint (@SitePoint) on CodePen.
offers scope for interesting animations, although it should only be relied on in modern browsers.
metric | effect |
---|---|
browser support | modern browsers only |
accessibility | content still read by some applications |
layout affected? | no — the original dimensions remain |
rendering required | paint |
performance | reasonable |
animation frames possible? | yes, in modern browsers |
events triggered when hidden? | no |
Absolute position
The property allows an element to be moved from its default position within the page layout using , , , and . An -positioned element can therefore be moved off-screen with or similar:
See the Pen hide with position: absolute by SitePoint (@SitePoint) on CodePen.
metric | effect |
---|---|
browser support | excellent, unless using |
accessibility | content still read |
layout affected? | yes, if positioning is changed |
rendering required | depends |
performance | reasonable if careful |
animation frames possible? | yes, on , , , and |
events triggered when hidden? | yes, but it may be impossible to interact with an off-screen element |
Setting Page and Post Visibility # Setting Page and Post Visibility
Visibility for posts and Pages is set from the Edit screen. The option is available under the “Publish” option normally found at the top-right of the Edit screen. The screenshot below shows the interface, with the relevant section highlighted in the red rectangle.
Publish metabox
The default state for post and Page visibility is Public. Public visibility means that the content will be visible to the outside world as soon as it is published.
By clicking on the edit link next to Visibility: Public in the Publish options, you can choose from an expanded selection of visibility options.
Publish metabox visibility options
The options are:
- Public: The default, viewable to all.
- Password Protected: Clicking this radio button followed by “OK” causes a further text box to appear, into which you can enter a password.
- Private: This option hides the content from the public completely.
Password Protected Content
Password Protected content is not immediately visible to the outside world. Instead, visitors will see a prompt similar to this:
Password protected page
The title for your protected entry is shown, along with a password prompt. A visitor to your site must enter the password in the box in order to see the content of the post or Page.
Private Content
Private content is published only for your eyes, or the eyes of only those with authorization permission levels to see private content. Normal users and visitors will not be aware of private content. It will not appear in the article lists. If a visitor were to guess the URL for your private post, they would still not be able to see your content. You will only see the private content when you are logged into your WordPress blog.
Publish metabox with visibility set to private
Once you change the visibility to private, the post or page status changes to “Privately Published” as shown. Private posts are automatically published but not visible to anyone but those with the appropriate permission levels (Editor or Administrator).
WARNING: If your site has multiple editors or administrators, they will be able to see your protected and private posts in the Edit screen. They do not need the password to be able to see your protected posts. They can see the private posts in the Edit Posts/Pages list, and are able to modify them, or even make them public. Consider these consequences before making such posts in such a multiple-user environment.
Low-level API
In some cases you may need more low-level methods. For example, you may want to count the time user has viewed the page in foreground and time it has stayed in background.
will return if browser supports the Page Visibility API:
if( Visibility.isSupported() ) { Statistics.startTrackingVisibility(); }
will return a string with visibility state. More states can be added in the future, so for most cases a simpler method can be used. It will return if the page is hidden by any reason. For example, while prerendering, will return , but will return .
This code will aid in collecting page visibility statistics:
$(document).load(function () { if ( 'hidden' == Visibility.state() ) { Statistics.userOpenPageInBackgroundTab(); } if ( 'prerender' == Visibility.state() ) { Statistics.pageIsPrerendering(); } });
And this example will only enable auto-playing when the page is opening as a visible tab (not a background one):
$(document).load(function () { if ( !Visibility.hidden() ) { VideoPlayer.play(); } });
Using you can listen to visibility state changing events. The takes 2 arguments: an event object and a state name.
Let’s collect some statistics with this events approach:
Visibility.change(function (e, state) { Statistics.visibilityChange(state); });
Method returns listener ID. You can use it to unbind listener by :
var listener = Visibility.change(function (e, state) { if ( !Visibility.hidden() ) { VideoPlayer.pause(); } }); VideoPlayer.onFinish(function () { Visibility.unbind(listener); });
Methods and will also return listener ID, if they wait visibility state changes. If they execute callback immediately, they return if Page Visibility API is supported and if they can’t detect visibility state.
var listener = Visibility.onVisible(function () { notification.takeAttention(); }); notification.onOutOfDate(function () { if ( typeof(listener) == 'number' ) { Visibility.unbind(listener); } });
ЕЩЁ
Полноэкранное видеоМодальное окноШкала времениИндикатор прокрутки Индикатор выполненияПанель навыковПолзунок диапазонаПодсказки при наведенииВсплывающие окнаСкладная секцияКалендарьВключить HTMLСписок делЗагрузчикиЗвездный рейтингПользовательский рейтингНаложениеКонтактные чипыКарточкиФлип-картаКарточка профиляКарточка товараОкно тревогиВыноска сообщенияПримечаниеМеткиКругиHR Горизонтальная линияКупонГруппа списковОтзывчивый текстВырезанный текстСветящийся текстФиксированный подвалЛипкий элементРавная высота столбцовОчистка поплавкаОтзывчивые поплавкиСнэк-бар/тостПолноэкранное режимЧертеж при прокруткеПлавная прокруткаГрадиент фонаЛипкий заголовокИзменить заголовок при прокруткеОтзывчивые столбцы ценПараллаксСоотношение сторонПереключатель нравится/не нравитсяПереключатель скрыть/показатьПереключаель текстаПереключатель классаДобавить классУдалить классАктивный классДревовидное представлениеУдалить свойствоАвтономный режим обнаруженияСделать скрытый элементПеренаправление веб страницыУвеличить при наведенииФлип-боксЭлемент вертикально по центруПереход при наведении курсораСтрелкиФигурыСсылка для скачиванияПолная высота элементаОкно браузераПользовательская полоса прокруткиРазличные устройстваЦвет заполнителяЦвет выделения текстаЦвет макераВертикальная линияАнимированные иконкиТаймер обратного отсчетаПишущая машинкаСтраница заставкиСообщение чатаВсплывающее окно чатаРазделенный экранРекомендацииСчетчик разделаСлайд-шоу цитатЗакрываемые злементы спискаТипичные точки прерыванияПеретаскиваемый HTML элементМедиа запросы JSПодсветка синтаксисаJS анимацииПолучить элементы Iframe
С этим читают
- :first-child
- Background-color
- How to add border to html table
- Css 3d transforms
- Border-image
- Css свойство padding-top
- Более 70 плагинов jquery скроллинга для вашего сайта
- Class yii\grid\actioncolumn
- Применение псевдоклассов в css для выборки элементов
- Оформляйте стили наведения, фокуса и активного состояния по-разному