Visibility или display в css

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()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
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()

Примеры

В следующем примере реализуется обработчик, который ссылается на две различные именованные кнопки, которые должны быть взаимоисключающими парами в пользовательском интерфейсе.The following example implements a handler that references two different named buttons that are intended to be a mutually exclusive pair in the user interface. Перед выполнением фактической логики программы, связанной с кнопкой, сама кнопка имеет значение , а вторая кнопка в паре имеет значение .Prior to running the actual program logic associated with the button, the button itself is set to be , and the other button in the pair is set to .

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

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 ScrollbarShow/Force 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 AnimationsJS String LengthJS ExponentiationJS Default ParametersGet Current URLGet Current Screen SizeGet Iframe Elements

Скрипт показывает блок только 1 раз 1 пользователю

По вот этому поисковому запросу наша страница индексируется :

скрипт который показывает блок только 1 раз 1 пользователюНаписание алгоритма :

Пользователь заходит на сайт.

Пользователю показывается какой-то блок информации 1 раз.

Значит, каким-тио образом, данные пользователя надо записать в память браузера, чтобы он понимал, что это именно тот пользователь, кому уже был показан данный блок!

Под данный вариант подходит несколько возможностей, для записи данных пользователя: 1). Сессия — действует до закрытия браузера. 2). Куки — время действия задается админом. 3). LocalStorage

CSS по стандартам

  • !important
  • @charset
  • @font-face
  • @import
  • @keyframes
  • @media
  • CSS свойства

    • по алфавиту
    • по категориям
    • все
    • CSS1
    • CSS2
    • CSS3
    • animation
    • animation-delay
    • animation-direction
    • animation-duration
    • animation-iteration-count
    • animation-name
    • animation-play-state
    • animation-timing-function
    • appearance
    • azimuth
    • backface-visibility
    • background
    • background-attachment
    • 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-shadow
    • box-sizing
    • break-after
    • break-before
    • break-inside
    • caption-side
    • clear
    • clip
    • color
    • column-count
    • column-gap
    • column-rule
    • column-rule-color
    • column-rule-style
    • column-rule-width
    • column-span
    • column-width
    • columns
    • content
    • counter-increment
    • counter-reset
    • cue
    • cue-after
    • cue-before
    • cursor
    • direction
    • display
    • elevation
    • empty-cells
    • float
    • font
    • font-family
    • font-size
    • font-size-adjust
    • font-stretch
    • font-style
    • font-variant
    • font-weight
    • height
    • 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
    • marquee-direction
    • marquee-play-count
    • marquee-speed
    • marquee-style
    • max-height
    • max-width
    • min-height
    • min-width
    • nav-down
    • nav-index
    • nav-left
    • nav-right
    • nav-up
    • opacity
    • orphans
    • 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
    • pause
    • pause-after
    • pause-before
    • pitch
    • pitch-range
    • play-during
    • position
    • quotes
    • resize
    • richness
    • right
    • speak
    • speak-header
    • speak-numeral
    • speak-punctuation
    • speech-rate
    • src
    • stress
    • table-layout
    • text-align
    • text-decoration
    • text-indent
    • text-overflow
    • text-shadow
    • text-transform
    • top
    • transition
    • transition-delay
    • transition-duration
    • transition-property
    • transition-timing-function
    • unicode-bidi
    • unicode-range
    • vertical-align
    • visibility
    • voice-family
    • volume
    • white-space
    • widows
    • width
    • word-spacing
    • word-wrap
    • z-index
  • Комментарии в CSS
  • Псевдоклассы

    • :active
    • :checked
    • :default
    • :disabled
    • :empty
    • :enabled
    • :first-child
    • :first-of-type
    • :focus
    • :hover
    • :in-range
    • :invalid
    • :lang
    • :last-child
    • :last-of-type
    • :link
    • :not
    • :nth-child
    • :nth-last-child
    • :nth-last-of-type
    • :nth-of-type
    • :only-child
    • :only-of-type
    • :optional
    • :out-of-range
    • :read-only
    • :read-write
    • :required
    • :root
    • :target
    • :valid
    • :visited
  • Псевдоэлементы

    • :after
    • :before
    • :first-letter
    • :first-line

Комментарии

Установка этого свойства влияет на значение IsVisible , которое, в свою очередь, может вызвать IsVisibleChanged событие.Setting this property affects the value of IsVisible, which in turn may raise the IsVisibleChanged event. Однако IsVisible имеет другие факторы, влияющие на него, например параметры видимости родительских элементов, содержащих его.However, IsVisible has other factors that influence it, for instance the visibility settings of parents that contain it.

Элементы Visibility , где не участвуют в событиях ввода (или командах), не влияют ни на меру, ни на перекомпоновку макета, а не на последовательность табуляции и не будут выводиться при проверке нажатия.Elements where Visibility is not do not participate in input events (or commands), do not influence either the Measure or Arrange passes of layout, are not in a tab sequence, and will not be reported in hit testing.

Если наследуется от Window или его производными классами, Window переопределяет значение этого свойства по умолчанию на .When inherited by Window or its derived classes, Window redefines the default value of this property to be . Это влияет на то, что не выполняет проход меры Layout в изначально созданном экземпляре Window , и RenderSize возвращает (0, 0).This has the effect of not running the Measure pass of layout on an initially created Window, and RenderSize returns (0,0). Дополнительные сведения см. в разделе Window.For details, see Window. Popup также переопределяет значение по умолчанию на , аналогичное результирующее поведение для Popup и его производных классов.Popup also redefines the default value to be , with similar resulting behavior for Popup and its derived classes.

Сведения о свойстве зависимостейDependency Property Information

Поле идентификатораIdentifier field VisibilityProperty
Свойства метаданных, для которых задано значение Metadata properties set to НетNone

Techniques for hiding content

There are several mechanisms that can be used for hiding content. It’s important that a technique be implemented that results in the desired outcome and accessibility.

or

These styles will hide content from all users. The content is removed from the visual flow of the page and is ignored by screen readers. Do not use this CSS if you want the content to be read by a screen reader. But DO use it for content you want hidden from all users.

attribute

The HTML attribute is relatively new and not supported on older browsers like IE11. When supported, it functions the same as CSS —elements with this attribute will not be presented to any user.

, or other 0 pixel sizing techniques (not recommended)

An element with no height or width, whether defined in HTML or CSS, is typically removed from the flow of the page, so most screen readers will not read it. Do not size content to 0 pixels if you want the content to be read by a screen reader. Content styled with or may work, though the elements would still take horizontal space on the screen. All these techniques may result in search engine penalties as they may be interpreted as malicious.

This approach moves the content to the left 10000 pixels — thus off the visible screen. Screen readers will still read text with this style.

However, if a link, form control, or other focusable element is given this style, the element would be focusable, but not visible on the page—sighted keyboard users would likely be confused. This approach may be a viable option if the element does not contain navigable elements, though better techniques are available.

Absolutely positioning content off-screen

The following are the recommended styles for visually hiding content that will be read by a screen reader.

.sr-only {
position:absolute;
left:-10000px;
top:auto;
width:1px;
height:1px;
overflow:hidden;}

The CSS class («sr-only» meaning «screen reader only», though the class name does not really matter) should then be referenced from within the tag of the element being hidden, as shown:

<div class=»sr-only»>This text is hidden.</div>

Sighted users will not see the hidden content at all—it will be hidden well to the left of the visible browser window. Because it is still part of the page content, screen readers will read it.

Let’s analyze the styles in detail. tells the browser to remove the element from the page flow and to begin positioning it. moves the content 10000 pixels to the left. tells the browser to position the content vertically at the same location it was originally. , and tell the browser to make the element one pixel in size and to visually hide everything that does not fit into that pixel—this is useful in instances where positioning may be end-user disabled, but all other styles remain enabled.

Note

Navigable elements, such as links and form controls, should not be hidden off-screen. They would still be navigable by sighted keyboard users, but would not be visible to them, unless they are styled to become visible when they receive keyboard focus.

CSS clip

{clip: rect(1px, 1px, 1px, 1px);
clip-path: inset(50%);
height: 1px;
width: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;}

Скрытие элементов

В CSS есть возможность временного или постоянного скрытия некоторых элементов веб-страницы

Стоит обратить внимание на то, что скрытые элементы не будут отображаться только на веб-странице, но их можно будет посмотреть в исходном коде HTML-документа. Для скрытия элементов используется или свойство со значением или свойство visibility со значением :

  • display: none; — указание браузеру скрыть элемент, убрав его из общего потока элементов. В этом случае элемент, расположенный после скрытого элемента, будет смещаться вверх, занимая место скрытого элемента.
  • visibility: hidden; — указание браузеру скрыть элемент, зарезервировав под него место на веб-странице. В этом случае браузер только скрывает элемент, не удаляя его из общего потока, поэтому на месте скрытого элемента останется пустое пространство, совпадающее по размеру с размером скрытого элемента.
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Название документа</title>
    <style>
      h1.hidden { visibility: hidden; }
      h2.none { display: none; }
    </style>
  </head>
  <body>
    <h1>Это видимый заголовок</h1>
    <h1 class="hidden">Скрытый заголовок</h1>
    <h2 class="none">Скрытый заголовок2</h2>
    <p>Элемент, который скрыт с помощью свойства visibility, все равно занимает
     пространство там, где он должен находиться в отличие от элемента скрытого с помощью
     свойства display, который убран из общего потока страницы.</p>
  </body>
</html>

Попробовать »

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients

CSS Shadows
Shadow Effects
Box Shadow

CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries

CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive

Override The Default Display Value

As mentioned, every element has a default display value. However, you can
override this.

Changing an inline element to a block element, or vice versa, can be useful for
making the page look a specific way, and still follow the web standards.

A common example is making inline elements for horizontal menus:

li {  display: inline;}

Note: Setting the display property of an element only changes how the element is displayed,
NOT what kind of element it is. So, an inline element with is not allowed
to have other block elements inside it.

The following example displays <span> elements as block elements:

span {  display: block;}

The following example displays <a> elements as block elements:

Override The Default Display Value

As mentioned, every element has a default display value. However, you can
override this.

Changing an inline element to a block element, or vice versa, can be useful for
making the page look a specific way, and still follow the web standards.

A common example is making inline elements for horizontal menus:

li {  display: inline;}

Note: Setting the display property of an element only changes how the element is displayed,
NOT what kind of element it is. So, an inline element with is not allowed
to have other block elements inside it.

The following example displays <span> elements as block elements:

span {  display: block;}

The following example displays <a> elements as block elements:

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients

CSS Shadows
Shadow Effects
Box Shadow

CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries

CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive

CSS Reference

CSS ReferenceCSS Browser SupportCSS SelectorsCSS FunctionsCSS Reference AuralCSS Web Safe FontsCSS Font FallbacksCSS 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

gap
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
row-gap

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

Fade-In and -Out by Combining Transitions on Visibility and Opacity

The opacity transition creates a nice fade-in and -out
effect. However fully transparent elements, unlike hidden elements,
still catch mouse events and older browsers fail completely
on opacity. A solution for these problems is to specify a
transition on both visibility and opacity. This
works fine and the following example shows how to do it:

<style >
   .cl1 { transition:visibility 1s, opacity 1s; 
            visibility:hidden; opacity:0}
   .outer1:hover > div 
         { visibility:visible; opacity:1}
</style>
 
<div class=»outer1″>
      <div class=»cl1″>

            Sample Text
      </div>

      Hover Here <br >

</div>

 

Sample Text

Hover Here

It also exposes and solves another
problem: if visibility is set to hidden the cl1 element does no longer act on
mouse events and so the cl0:hover as used in the first
example never applies. So we put another div of
class outer1 around the sample element and use a rule
.outer1:hover > div which means that whenever the mouse
hovers the outer element then the inner div should get the
specified format.

Other solutions for these problems are discussed in .

Using CSS Transitions on the Transform Property to Fly In

Basic idea of this work around for visibility:hidden
is to use the CSS transition property to move the element
outside the document. This works nicely in newer browsers
and allows for interesting animations.

For older browsers you probably need workarounds as in .
It is clear that for browsers like IE 8 transitions do not work.
However most of the examples in the article still show and hide the elements
in IE8, just without animation. This is however not the case for the
two following examples (and also not for the first opacity example).

2D Example

The following examples show a fly in animation in 2D and then in 3D:

<style >
   .cl12           { width:80%; padding:10%; background‑color:yellow;
      transform:translate(‑1300px, px) rotate(180deg);
      transition‑property:all;  transition‑duration:5s;}
   .outer12     {  width:90%; height:100px;}
   .outer12:hover > div { transform:translate( px,0px); }
</style>
 
<div class=»outer12″>
      <div class=»cl12″>

            Sample Text
      </div>

      Hover Here
</div>

 

Sample Text

Hover Here

3D Example

<style >
   .cl13           { width:80%; padding:10%; background‑color:yellow;
                       transform:translate3d(‑300px, 20px, 2000px) rotateY(‑180deg);
                       transition‑property:all; transition‑duration:5s;}
   .outer13     {  width:90%; height:100px; perspective:2300px;}
   .outer13:hover > div { transform:translate3d( px, px, 100px) }
</style>
 
<div class=»outer13″>
      <div class=»cl13″>

            Sample Text
      </div>

      Hover Here
</div>

 

Sample Text

Hover Here

Alternatively such an animation can be done with WebGL and taccgl.
This has the additional advantage of automatic lighting and shadows.
Lighting simulates a virtual light source and calculates the color for every
pixel of the animated element. So for instance an element that directly
faces the light source appears brighter than an element that rotates away.
This leads to a much more realistic rotation effect.

taccgl.a(document.body) .color(«white») .shadowOnly() .dur(4) .start();
a=taccgl.actor(«demo», null, «visible»);;
a.posZ(100) .resizeZ() .from(-200,a.y-20,1400).

rotateMiddle(0,1,0) .rotatePart(Math.PI,2*Math.PI) .vEnd(0,0,0) .dur(4) .start()

RUN

Как скрыть элемент использую присвоение классов в jQuery

Один из самых «нормальных» вариантов это присваивать временные классы. Кстати говоря, такие классы лучше выделить как-то на фоне остальных, например, мне понравилась идея добавлять приставку .js- как по мне, очень удобно.

В самом начале статьи уже рассматривались варианты скрытия на CSS, самый адекватный это:

.js-hidden {
  display: none;
}

и как всегда вся магия jQuery умещается в несколько строк:

$(function(){
  $('.my-selector').click(function(){
    $(this).addClass('js-hidden');
    $(this).removeClass('js-hidden');
    $(this).toggleClass('js-hidden');
  });
});

$(this).addClass(‘js-hidden’); — добавляем класс тому объекту, по которому мы кликнули,$(this).removeClass(‘js-hidden’); — убираем класс по клику,$(this).toggleClass(‘js-hidden’); — автоматом убираем или добавляем класс, по очереди.

Обратите внимание, что если вы хотите закрыть «попап» или другой элемент на странице, вам нужно заменить $(this) на свой селектор $(‘.mySelector’), и не забывайте, одну очень важную вещь — прятать нужно не все элементы на странице, а только тот, который относится к текущей кнопке. Да, это означает что вам придется искать родителя, начиная от элемента по которому вы кликнули

Надеюсь, вы сами разберетесь какие из этих советов можно считать «вредными», а какие можно смело применять

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector