Использование css переходов

Old Opacity Settings

Here are the old opacity settings that were required for older versions of Firefox and Safari:

.myElement {
  -khtml-opacity: .5;
  -moz-opacity: .5;
}

The setting was for older versions of the webkit rendering engine, and was necessary in order to get older versions of Safari to work. This proprietary property is now obsolete and is no longer needed unless you know that you have a significant amount of web traffic coming from visitors using Safari 1.x., which is highly unlikely.

The next line uses the proprietary property , which was aimed at very early versions of the Mozilla rendering engine, and dates back even to Netscape Navigator. Firefox stopped requiring the property since Firefox 0.9. Firefox 3.5 (now using the Gecko engine) has dropped support for this property.

Прозрачность картинки

Для создания эффекта прозрачности в CSS используется свойство opacity.

Браузер IE8 и более ранние его версии поддерживают альтернативное свойство — , где «» может принимать значение от до , чем меньше значение, тем прозрачнее будет элемент.

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

<!DOCTYPE html>  <html>    <head>      <meta charset="utf-8">      <title>Название документа</title>      <style>        .myClass {          float: left;          margin-right: 5px;          opacity: 0.4;          filter: alpha(opacity=40); /*для IE8 и более ранних версий*/        }      </style>    </head>      <body>      <img src="klematis.jpg" class="myClass">  	<img src="klematis.jpg">    </body>  </html>  

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

Повышение универсальности кода

Если же программист желает оптимизировать свой контент для более старых приложений, ему необходимо будет изучить дополнительные стили.

Для Internet Explorer версии 5.5 и выше воспринимаемым кодом является весьма длинная и некрасивая строчка — «filter:progid:DXImageTransform.Microsoft.Alpha(opacity=X)», где параметр прозрачности необходимо указывать уже не в долях от единицы, а в сотнях. Его максимальное значение, при котором прозрачность цвета CSS-объекта становится полной, составляет 100.

Собственный код существует и для менее популярных браузеров. Одним из таких является Konqueror, больше известный пользователям рабочей среды KDE на UNIX-подобных системах. Для него прозрачность CSS потребуется прописать параметром «-khtml-opacity: 0.X».

Для полной уверенности в оптимизации своего кода можно добавить строчку, обеспечивающую поддержку одних из первых версий браузеров Mozilla: «-moz-opacity: 0.X».

Выполнив подобную оптимизацию, web-мастер сможет добиться правильного отображения своего контента на большинстве пользовательских устройств.

CSS Свойства

align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingcaption-sidecaret-color@charsetclearclipcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-weightgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerighttab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index

Активность при наведении

Так как CSS-прозрачность чаще всего используется как оформление для элементов с гиперссылками, то активность при наведении на них становится одной из первостепенных задач. В качестве примера можно рассмотреть тот же прямоугольник. Допустим, необходимо, чтобы при наведении на блок прозрачность менялась с 0 до значения 0.5. Для получения такой возможности понадобится всего лишь занести уже имеющийся стиль, отвечающий за прозрачность, под дополнительный CSS-параметр hover. Данным свойством пользуются и для добавления таких эффектов, как изменение цвета и формы объектов при наведении

Это позволяет сделать необходимые области визуально активными, привлекая внимание посетителей к ссылкам или контенту

Alternative solution: add an overlay with reduced opacity and background-color on top of the background image.

Another solution is instead of changing the opacity of the background image, you add an overlay with a semi-transparent background color on top of the background image.

The HTML markup will be the same as the previous solution. In the CSS, you can set the background-image directly in the parent element, with no opacity change.

The pseudo-element of the parent will then contain the semi-transparent background-color.

This is accomplished by setting the  property using the , where the first three characters are the RGB color numbers, and the last number is the alpha or transparency setting. We’re using  for the RGB color, which translates to black.

An alpha value can range from  (0% opacity) to  (100% opacity). So our value of will result in an overlay of 25% opacity.

Here’s what that will look like in the code:

The result will look like this:

And here’s the Codepen for this overlay solution!

Both solutions have a very similar-looking result. The first solution has a background image set at 75% opacity. And the second solution adds a black overlay at 25% opacity. So they’re not quite the same, but they are similar.

The overlay solution is also handy if you want to add a toned color to the background image. Here’s what that would look like if we set the overlay  to :

:hover для простой смены прозрачности

Ещё отмечу, что для простой смены прозрачности (но не постепенного её изменения) в самый раз подходит псевдо-селектор :hover, который позволяет определить стили для элемента, в момент наведения на него мыши.

<style type="text/css">
a:hover img {
  filter:progid:DXImageTransform.Microsoft.Alpha(opacity=30);
  -moz-opacity: 0.3;
  -khtml-opacity: 0.3;
  opacity: 0.3;
}
</style>

<a href="javascript:void(0)">
<img src="/images/articles/strawberry.jpg" width="100" height="80" />
</a>

Обратите внимание, что картинка размещена внутри элемента A. Дело в том, что Internet Explorer вплоть до версии 6, понимает псевдо-селектор :hover, только применительно к ссылкам, а не к любым элементам, как положено в CSS (в IE7 положение исправлено)

Создание полупрозрачного фона в CSS

Полупрозрачный элемент хорошо заметен на фоновом рисунке. В веб-дизайне полупрозрачность достигается за счёт свойства opacity или задаваемого для фона формата цвета RGBA.

Особенность данного свойства заключается в том, что прозрачность действует не только на фон, но и на все дочерние элементы. После увеличения прозрачности, и текст и фон станут полупрозрачными.

Пример создания полупрозрачного блока:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>opacity</title>
  <style>
   body {
    background: url("http://cs614726.vk.me/v614726246/4a02/300wj_aFOK4.jpg");
    background-size: 10% auto;
   }
   div {
	 opacity: 0.7;
 	 background: #717ceb; /* Цвет фона */
 	 padding: 20px; /* Поля вокруг текста */
   }
  </style>
 </head>
 <body>
   <div>Так выглядит полупрозрачный блок.</div>
 </body>
</html>

Однако достаточно часто полупрозрачным должен быть только фон определённого элемента, а текст оставаться непрозрачным для читабельности.

В таком случае opacity не подходит и следует воспользоваться форматом RGBA, в котором помимо значений яркости синего, красного и зелёного цветов устанавливается ещё и значение прозрачности. 1 означает абсолютную непрозрачность, а 0 — полную прозрачность.

Пример задания прозрачного фона:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>rgba</title>
  <style>
   body { 
  background: url("http://cs614726.vk.me/v614726246/4a02/300wj_aFOK4.jpg");
  background-size: 20% auto;
}
   div {
    background: rgba(60, 150, 250, 0.7); /* Цвет фона */
    color: #fff; /* Цвет текста */
    padding: 20px; /* Поля вокруг текста */
   }
  </style>
 </head>
 <body>
  <div>Прозрачный фон блока и непрозрачный текст.</div>
 </body>
</html>

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

РМРимма Михайловаавтор

CSS Opacity in Firefox, Safari, Chrome, and Opera

Here is the simplest and most up to date syntax for CSS opacity in all current browsers except Internet Explorer:

.myElement {
  opacity: .7;
}

The syntax above will set an element to 70% opacity (or 30% transparency). A setting of would make the element opaque, whereas a setting of would make the element completely invisible. This is easy to remember if you keep in mind that the word “opacity” comes from the word “opaque”, which is the opposite of “transparent”. The lower the opacity (or “opaqueness”), the closer you’ll be to transparency.

The property can be set to two decimal places, so a value of “.01” would be different from a value of “.02”, although the visible difference would be very hard to notice. Generally, it’s best to stick to one decimal place, using values like “.3” or “.7”.

CSS Opacity in Internet Explorer

As usual, Internet Explorer doesn’t play well with others, and since there are currently three different versions of Internet Explorer in common use, the transparency settings are different, and sometimes require additional CSS to get them to work.

.myElement {
  filter: alpha(opacity=40);
}

The above css uses the proprietary property to get transparency to work in Internet Explorer versions 6-8. There is one caveat for IE6 and IE7: In order for the transparency settings to take effect, the element in question needs to “have layout”. An element can be given layout using a number of CSS properties, including and . For details on the Microsoft-only property, and how to trigger it, see this article.

Another way to set transparency via CSS in Internet Explorer 8 uses the following syntax (note the comments that indicate which versions):

.myElement {
  filter: progid:DXImageTransform.Microsoft.Alpha(opacity=40);
  /* above line works in IE6, IE7, and IE8 */
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=40)";
  /* above line is IE8 only */
}

The first line will work in all currently-in-use versions of IE, and the second line works only in IE8. Notice the differences between the two lines: In line two, there is a prefix attached to the property, and there are quotations around the entire value declaration, both of which are necessary for that syntax to work.

To be honest, I really have no idea why you would even need either of the “progid” methods, since the filter property works on any element that has layout in all versions of IE using the syntax , as shown in the first example in this section.

Update: Evidently, in order to get IE8 in compatibility mode to recognize opacity settings, you need to do the following, in this order:

.myElement {
  -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(opacity=40)";
  filter: alpha(opacity=40);
}

Basically, if you’re including the IE8-as-IE7 meta tag in your site’s code, or you’re worried that IE8 users will be hitting the compatibility mode button, then this would be necessary. Otherwise, just use the plain method (first example).

Thanks to the comment for providing the source for this info. I haven’t actually tested to confirm this, but the referenced website is quite reliable, so I will assume it’s correct.

Использование css-свойства opacity

Opacity является универсальным инструментом, и с его помощью вы можете задать желаемый уровень прозрачности в css как для любого элемента на странице, так и для фона.

Синтаксис свойства css:

opacity: значение;

где значение указывается в диапазоне от 0.0 (элемент полностью прозрачен) до 1.0 (элемент абсолютно не прозрачен).

Итак, для примера сделаем блок с классом fon, и для него зададим, для наглядности, фоновое изображение. В этом блоке разместим два блока с текстом opas1 и opas2, для которых зададим черный фон. После чего для второго блока зададим значение opacity равное 0.3.

Вот что получится:

Блок без прозрачности

Демонстрация работы свойства css opacity

HTML-код примера:

XHTML

<div class=»fon»>
<div class=»opas1″>
Блок без прозрачности
</div>
<div class=»opas2″>
Демонстрация работы свойства css opacity
</div>
<div>

1
2
3
4
5
6
7
8
9
10
11

<div class=»fon»>

<div class=»opas1″>

Блок без прозрачности
</div>
 

<div class=»opas2″>

Демонстрация работы свойства css opacity
</div>
 
<div>

CSS-код:

CSS

.fon{
background:url(images/opacity1.jpg);
width:400px;
padding:30px;
margin:auto;
}
.opas1{
width: 300px;
padding:30px;
background:#000;
margin:auto;
text-align:center;
margin:10px;
font-size:18px;
color:#fff;
}
.opas2{
width: 300px;
padding:30px;
background:#000;
margin:auto;
text-align:center;
opacity:0.3; /* уровень прозрачности в css*/
margin:10px;
font-size:18px;
color:#fff;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

.fon{

backgroundurl(images/opacity1.jpg);

width400px;

padding30px;

marginauto;

}
 

.opas1{

width300px;

padding30px;

background#000;

marginauto;

text-aligncenter;

margin10px;

font-size18px;

color#fff;

}
 

.opas2{

width300px;

padding30px;

background#000;

marginauto;

text-aligncenter;

opacity0.3;/* уровень прозрачности в css*/

margin10px;

font-size18px;

color#fff;

}

Как видите, свойство css сработало, блок с классом opas2 стал прозрачным и через него проглядывается фоновое изображение.

Но здесь есть один неприятный момент. Как вы могли заметить, текст потускнел, то есть он тоже стал прозрачным. Это произошло из-за того, что все дочерние элементы блока, в нашем случае – текст, унаследовали прозрачность заданную в css.

Получается, что данное css-свойство мы можем использовать для придания прозрачности блоку на странице только в том случае, если он не содержит никакого текста.

А что же делать, если нам нужно задать в css прозрачность фона для блока, но при этом сохранить читабельность содержащегося в нем текста?

CSS Tutorial

CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL

CSS Backgrounds
Background
Color
Background Image
Background Repeat
Background Attachment
Background Shorthand

CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders

CSS Margins
Margins
Margin Collapse

CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset

CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow

CSS Fonts
Font Family
Font Web Safe
Font Fallbacks
Font Style
Font Size
Font Google
Font Pairings
Font Shorthand

CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive

CSS DisplayCSS Max-widthCSS PositionCSS Z-indexCSS OverflowCSS Float
Float
Clear
Float Examples

CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar

CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS SpecificityCSS !importantCSS Math Functions

CSS opacity симбиоз

Под симбиозом я подразумеваю объединение разных стилей для разных браузеров в одном CSS правиле для получения нужного эффекта, т.е. для реализации кросс-браузерности.

filter:progid:DXImageTransform.Microsoft.Alpha(opacity=50); /* IE 5.5+*/
-moz-opacity: 0.5; /* Mozilla 1.6 и ниже */
-khtml-opacity: 0.5; /* Konqueror 3.1, Safari 1.1 */
opacity: 0.5; /* CSS3 - Mozilla 1.7b +, Firefox 0.9 +, Safari 1.2+, Opera 9 */

По сути, нужными являются первое и последнее правила, для IE5.5+ и браузеров понимающих CSS3 opacity, а два правила по середине явно погоды не делают, но и не очень то и мешают (сами решайте, нужны ли они вам).

Use a Lower Opacity CSS Pseudo Element to Create a Colored Background Layer

Let’s suppose you have the following elements; a content child element nested inside a parent element:

<div id="parent">
  <div id="child">
    Text
  </div>
</div>

With a structure like that, you can create a background layer (having no content) via CSS pseudo elements like so:

#parent::after { content: ''; }

Now you can make the background layer the same size as the parent and position it relative to the parent like so:

#parent { height: 45px; position: relative; }
#parent::after {
	content: ''; 
	width: 100%; 
	height: 100%;
	background-color: pink; 
	opacity: 0.5; 
	position: absolute; 
	top: 0; 
	left: 0;
	z-index: -1;
}

You should now see a pink colored background layer with an opacity of 50% that only applies to the background color and not the content.

Following is a quick explanation of how the generated content (our background layer) is styled:

  • To generate empty/invisible content we can simply set the property’s value to an empty string or a space character.
  • Setting and to ensures the generated content is of the same size as the parent element.
  • Setting a lower makes the background layer transparent.
  • on the parent element and on the generated content ensures the generated content is positioned relative to the parent.
  • Setting and ensures the generated content is positioned to the top left edge of the parent element.
  • Setting a negative value ensures the generated content recedes to the background and all child element content appears above it.

If the parent element has a background color of its own, then you can set a positive value on the generated content (the background layer) and a higher z-index value on the child element along with relative positioning like so:

#parent { height: 45px; background-color: yellow; position: relative; }
#parent::after {
	content: ''; 
	width: 100%; 
	height: 100%; 
	background-color: pink; 
	opacity: 0.5; 
	position: absolute; 
	top: 0; 
	left: 0; 
	z-index: 1;
}
#child {position: relative; z-index: 2;}

Последние поступления:

Размещена 10 августа 2020 года

Я по ТВ видел, что через 10 лет мы будем жить лучше, чем в Германии…
Я не понял, что это они с Германией сделать хотят?!

Размещена 14 марта 2018 года

Пpоект Genesis (из коpпоpативной пеpеписки)

Шпаргалка по работе с Vim

Размещена 05 декабря 2017 года

Vim довольно мощный редактор, но работа с ним не всегда наглядна.
Например если нужно отредактировать какой-то файл например при помощи crontab, без знания специфики работы с viv никак.

Ошибка: Error: Cannot find a valid baseurl for repo

Размещена 13 сентабря 2017 года

Если возникает ошибка на centos 5 вида
YumRepo Error: All mirror URLs are not using ftp, http or file.
Eg. Invalid release/

Opacity

The CSS property sets the opacity for
the whole element (both background color and text will be opaque/transparent).

The property value must be a number between 0.0 (fully transparent) and 1.0 (fully opaque).

rgb(255, 0, 0);opacity:0.2;
rgb(255, 0, 0);opacity:0.4;
rgb(255, 0, 0);opacity:0.6;
rgb(255, 0, 0);opacity:0.8;

Notice that the text above will also be
transparent/opaque!

The following example shows different elements with opacity:

Example

#p1 {background-color:rgb(255,0,0);opacity:0.6;}  /* red with opacity
*/#p2 {background-color:rgb(0,255,0);opacity:0.6;}  /* green with
opacity */#p3 {background-color:rgb(0,0,255);opacity:0.6;}  /* blue
with opacity */

❮ Previous
Next ❯

Setting and Changing CSS Opacity with jQuery

Setting CSS opacity directly using jQuery is much more practical and easier to implement, because the code is exactly the same for all browsers, and you don’t have to worry about an element “having layout” in IE:

$(".myElement").css({ opacity: .4 }); // works in all browsers

You can also animate the opacity of an element using the following jQuery code:

$(".myElement").animate({
  opacity: .4
  }, 1000, function() {
  // Animation complete; works in all browsers
});

Whatever the opacity of the element is when the animation begins, it will animate until it reaches an opacity level of “.4”. The speed of the animation is set using the value “1000”, which is the duration of the animation in milliseconds. The final property listed is an optional callback function that will run some code when the animation is complete.

If the opacity of this element is already set to “.4” in the CSS, then you won’t notice any difference when the animation runs, so the animated value has to be something significantly different.

Тени

Спецификация CSS3 определяет два новых типа теней: блочные тени (box shadows) и текстовые тени (text shadows). Блочные тени обычно более полезны и имеют более высокий уровень поддержки, в то время как текстовые тени не работают ни в одной из версий Internet Explorer. Блочную тень можно использовать для создания прямоугольной тени позади любого блока элемента <div> (но не забудьте при этом о рамке, чтобы он продолжал выглядеть как блок). Тени могут даже следовать контурам блоков со скругленными углами:

Рассматриваемые тени создаются посредством свойств box-shadow и text-shadow. Далее приведен пример создания базовой блочной тени:

Первые два значения свойства box-shadow устанавливают горизонтальное и вертикальное смещения тени от исходного объекта. Положительные значения смещают тень вниз и вправо, отрицательные — вверх и влево. Следующее значение определяет размер размытия (blur, в данном примере 10 пикселов), которое увеличивает расплывчатость тени. Последнее значение определяет цвет тени. Если под блоком находится какое-либо содержимое, подумайте об использовании функции rgba(), чтобы сделать тень полупрозрачной.

Для более тонкой настройки тени в свойство box-shadow можно добавить два значения. Чтобы установить ширину (spread) тени — подсвойство, которое расширяет тень, утолщая ее сплошную часть между размытыми краями, добавляется значение между значениями размытия и цвета:

А чтобы создать тень, отражающуюся не наружу, а внутрь элемента, в конце списка значений добавляется значение inset. Лучший эффект достигается, когда тень располагается непосредственно поверх элемента, без горизонтального или вертикального смещения:

Свойство text-shadow требует подобного набора значений, но в другом порядке. Сначала указывается цвет, за ним следует горизонтальное и вертикальное смещения, а потом размытие:

Как работает непрозрачность в CSS

Термин «непрозрачный» используется для описания объектов, которые полностью видимые. На веб-странице непрозрачный элемент имеет значение свойства opacity 1, а полностью прозрачный — opacity, равное . По умолчанию все элементы имеют opacity, равное 1.

Значение от до 1 определяет уровень прозрачности элемента. Например, следующий код уменьшит прозрачность CSS наполовину:

div { opacity: 0.5 }

Элемент с непрозрачностью будет полностью невидимым, но он все равно будет занимать физическое пространство на странице. Следовательно, чтобы сделать элемент видимым, нужно использовать в CSS свойство opacity, а также свойство visibility.

opacity было введено в CSS3 и на сегодняшний день хорошо поддерживается браузерами. Если ваш проект требует поддержки Internet Explorer 8 или более ранних версий, то нужно использовать свойство MS alpha filter следующим образом:

div {
  opacity: 0.5;
  filter: alpha(opacity=50);
}

Обратите внимание, что прозрачность фона CSS может задаваться десятичными значениями от до 1, а значения непрозрачности альфа-фильтра — в диапазоне от 0% до 100%

Плавное изменение прозрачности элемента

Готовое решение. Используем библиотеку opacity.js

<html>
<head>
<!-- Устанавливаем изначальную прозрачность картинок -->
<style type="text/css">
  img {
    filter:alpha(opacity=30);
    -moz-opacity: 0.3;
    -khtml-opacity: 0.3;
    opacity: 0.3;
  }
</style>

<!-- Подключаем библиотеку -->
<script type="text/javascript" src="/js/opacity.js"></script>

<script type="text/javascript">
// Создаем правило изменения прозрачности: задаем имя правила, начальную и конечную прозрачность, а также необязательный параметр задержки влияющий на скорость смены прозрачности
  fadeOpacity.addRule('oR1', .3, 1, 30);
</script>

</head>
<body>

<img id="fImg1" onMouseOver="fadeOpacity(this.id, 'oR1')"  onmouseout="fadeOpacity.back(this.id)" src="/img/strawberry.jpg" width="100" height="80" />
<img id="fImg2" onMouseOver="fadeOpacity(this.id, 'oR1')"  onmouseout="fadeOpacity.back(this.id)" src="/img/tomato.jpg" width="82" height="100" />
<img id="fImg3" onMouseOver="fadeOpacity(this.id, 'oR1')"  onmouseout="fadeOpacity.back(this.id)" src="/img/sweet_cherry.jpg" width="98" height="97" />

</body>
</html>

Основные шаги:

  1. Подключаем библиотеку функций;
  2. Определяем правила;
  3. Вызываем метод fadeOpacity() для перетекания цвета от начального к конечному, или fadeOpacity.back() для возврата к начальному цвету.

Разжевываем

Как подключать библиотеку, думаю, видно из примера выше. Теперь стоит пояснить определение правил. До того как вызывать методы плавного изменения прозрачности, нужно определить правила, по которым будет выполняться процесс: нужно определить начальную и конечную прозрачность, а также, при желании, указать параметр задержки, который влияет на скорость процесса смены прозрачности.

Правила определяются с помощью метода fadeOpacity.addRule

Синтаксис: fadeOpacity.addRule (sRuleName, nStartOpacity, nFinishOpacity, nDalay)

Аргументы:

  • sRuleName — имя правила, задаётся произвольно;
  • nStartOpacity и nFinishOpacity — начальная и конечная прозрачность, числа в диапазоне от 0.0 до 1.0 ;
  • nDelay — задержка в миллисекундах (необязательный аргумент, по умолчанию равен 30).

Сам вызов фейдинга прозрачности делаем через методы fadeOpacity(sElemId, sRuleName), где sElemId это id элемента, а sRuleName имя правила. Для возврата прозрачности в исходное состояние используется метод fadeOpacity.back(sElemId).

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
caption-side
caret-color
@charset
clear
clip
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-kerning
font-size
font-size-adjust
font-stretch
font-style
font-variant
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
object-fit
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
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
z-index

Transparency using RGBA

If you do not want to apply opacity to child elements, like in our example above, use RGBA color values.
The following example sets the opacity for the background color and not the text:

100% opacity

60% opacity

30% opacity

10% opacity

You learned from our CSS Colors Chapter, that you can use RGB as a color value. In addition to RGB,
you can use an RGB color value with an alpha channel (RGBA) — which specifies the opacity for a color.

An RGBA color value is specified with: rgba(red, green, blue, alpha). The
alpha parameter is a number between 0.0 (fully transparent) and 1.0 (fully opaque).

Tip: You will learn more about RGBA Colors in our CSS Colors Chapter.

RGBA Colors

RGBA color values are an extension of RGB color values with an alpha channel — which specifies the opacity
for a color.

An RGBA color value is specified with: rgba(red, green, blue, alpha). The alpha parameter is a number between 0.0
(fully transparent) and 1.0 (fully opaque).

rgba(255, 0, 0, 0.2);
rgba(255, 0, 0, 0.4);
rgba(255, 0, 0, 0.6);
rgba(255, 0, 0, 0.8);

The following example defines different RGBA colors:

Example

#p1 {background-color: rgba(255, 0, 0, 0.3);}  /* red
with opacity */#p2 {background-color: rgba(0, 255, 0, 0.3);}  /* green with opacity */#p3 {background-color: rgba(0, 0, 255, 0.3);}  /* blue
with opacity */

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

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

Adblock
detector