Css при наведении добавить класс

:hover¶

Псевдокласс :hover срабатывает, когда пользователь наводит на элемент мышью, но не обязательно активирует его.

Демо¶

Этот стиль может переопределяться другими относящимися к ссылкам псевдоклассами, такими как :link , :visited и :active , появляющимися в соответствующем порядке. Чтобы стилизировать ссылки должным образом, вам нужно вставлять правило :hover до правил :link и :visited , но после :active , как определено в LVHA-порядке: :link — :visited — :hover — :active .

Псевдокласс :hover может применяться к любому псевдоэлементу.

Браузеры, такие как Firefox, Internet Explorer, Safari, Opera или Chrome, применяют соответствующий стиль, когда курсор (указатель мыши) наводится на элемент.

Замечания по использованию

На сенсорных экранах :hover проблемный или не работает. В зависимости от браузера, псевдокласс :hover может никогда не сработать, или сработать на некоторое время после нажатия на элемента, или может продолжать действовать даже остаться после того, как пользователь коснулся элемента до нажатия на другой элемент. Так как сенсорные устройства очень распространены, то веб-разработчикам очень важно не иметь контент, доступный только при наведении, так как такой контент неудобно или невозможно использовать на таких устройствах.

Синтаксис¶

Спецификации¶

Описание и примеры¶

Пример 1. Выпадающее меню¶

С псевдоклассом :hover вы можете создавать сложные каскадные алгоритмы. Эта техника часто используется, например, чтобы создать выпадающие меню на чистом CSS (только на CSS, без использования JavaScript). Сущность этой техники — создание правил, типа следуюшего:

div.menu-bar ul ul  display: none; > div.menu-bar li:hover > ul  display: block; > 
 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 30 31
div class="menu-bar"> ul> li> a href="example.html">Менюa> ul> li> a href="example.html">Ссылкаa> li> li> a class="menu-nav" href="example.html" >Подменюa > ul> li> a class="menu-nav" href="example.html" >Подменюa > ul> li>a href="example.html">Ссылкаa>li> li>a href="example.html">Ссылкаa>li> li>a href="example.html">Ссылкаa>li> li>a href="example.html">Ссылкаa>li> ul> li> li>a href="example.html">Ссылкаa>li> ul> li> ul> li> ul> div> 

Смотрите полный пример выпадающего меню, основанный на CSS.

Пример 2. Галерея полноразмерных изображений и превью¶

Вы можете использовать псевдокласс :hover , чтобы создать галерею изображений с полноразмерными картинками, показываемыми при наведении на них мыши. Посмотрите это демо.

Пример 3¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
 html> head> meta charset="utf-8" /> title>hovertitle> style> a:link  color: #0000d0; /* Цвет ссылок */ padding: 2px; /* Поля вокруг текста */ > a:hover  background: #786b59; /* Цвет фона под ссылкой */ color: #ffe; /* Цвет ссылки */ > style> head> body> p>a href="1.html">Ссылка 1a>p> p>a href="2.html">Ссылка 2a>p> p>a href="3.html">Ссылка 3a>p> body> html> 

В данном примере псевдокласс :hover применяется к ссылке (тегу ), при этом меняется цвет ссылки и фона под ней. Результат:

Результат использования псевдокласса :hover для ссылок

Пример 4¶

 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 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
 html> head> meta charset="utf-8" /> title>hovertitle> style> ul  width: 180px; /* Ширина меню */ list-style: none; /* Для списка убираем маркеры */ margin: 0; /* Нет отступов вокруг */ padding: 0; /* Убираем поля вокруг текста */ font-family: Arial, sans-serif; /* Рубленый шрифт для текста меню */ font-size: 10pt; /* Размер названий в пункте меню */ > li ul  position: absolute; /* Подменю позиционируются абсолютно */ display: none; /* Скрываем подменю */ margin-left: 165px; /* Сдвигаем подменю вправо */ margin-top: -2em; /* Сдвигаем подменю вверх */ > li a  display: block; /* Ссылка как блочный элемент */ padding: 5px; /* Поля вокруг надписи */ text-decoration: none; /* Подчеркивание у ссылок убираем */ color: #666; /* Цвет текста */ border: 1px solid #ccc; /* Рамка вокруг пунктов меню */ background-color: #f0f0f0; /* Цвет фона */ border-bottom: none; /* Границу снизу не проводим */ > li a:hover  color: #ffe; /* Цвет текста активного пункта */ background-color: #5488af; /* Цвет фона активного пункта */ > li:hover ul  /* При выделении пункта курсором мыши отображается подменю */ display: block; > .brd  border-bottom: 1px solid #ccc; /* Линия снизу */ > style> head> body> ul class="menu"> li> a href="russian.html">Русская кухняa> ul> li>a href="linkr1.html">Бефстрогановa>li> li>a href="linkr2.html">Гусь с яблокамиa>li> li> a href="linkr3.html">Крупеник новгородскийa> li> li> a href="linkr4.html" class="brd" >Раки по-русскиa > li> ul> li> li> a href="ukrainian.html">Украинская кухняa> ul> li>a href="linku1.html">Вареникиa>li> li> a href="linku2.html">Жаркое по-харьковскиa> li> li> a href="linku3.html">Капустняк черниговскийa> li> li> a href="linku4.html" class="brd" >Потапцы с помидорамиa > li> ul> li> li> a href="caucasus.html">Кавказская кухняa> ul> li>a href="linkc1.html">Суп-харчоa>li> li>a href="linkc2.html">Лилибджa>li> li>a href="linkc3.html">Чихиртмаa>li> li> a href="linkc4.html" class="brd">Шашлыкa> li> ul> li> li> a href="asia.html" class="brd" >Кухня Средней Азииa > li> ul> body> html> 

Источник

CSS Class Hover

CSS Class Hover

This blog will demonstrate the use of hover effect in CSS on various elements on an html page. To understand the Hover effect we have to first understand the word Hover. Hover means when we move our mouse cursor to an element on a web page. If the programmer has programmed an hover effect then that element will change its appearance.

We will learn how to bring a hover effect on the elements with the help of classes applied on various elements like div, a & button elements.

Contents

CSS – Div class hover

Hover effect can be directly given to the elements but when it is applied to a particular element like div then the hover effect will be reflected to all the div elements.

Using a class to apply the hover effect, gives us a choice to apply it on selective elements. We need to just add the class name to the element to apply the effect.

Hover effect is basically used to highlight the element by changing its appearance & it also gives the user a confirmation that he is positioned to that particular element.

To demonstrate with an example, we will look into the div tag & apply the hover effect with the help of class.

CSS :-

HTML :-

 
I am Hover Div.
I am Non Hover Div.

Result :-

In the CSS section, in the second style we have defined a hover effect that will be applied on div tags having class name as hoverdivs .

div.hoverDivs is concerned with the selection of elements.

:hover is used to apply the hover effect.

On hover effect, we are changing the background color of the div to red & text color to white. We are also changing the style of the text to italics.

The HTML section has 2 divs. Last one is without any class & the first one is given the class name of hoverDivs .

In the result image, we can see that only the first div element is receiving the hover effect. And the second div remains unaffected because we have applied hover effect to only specified class name.

CSS – Anchor class hover

Anchor tags are used to navigate the user to some other page or to some other region in the same page. Another page can be of the same website or it may be of some external website.

Anchor tags are important because we are inviting the user to check out some other content. For the user to know the link is clickable, we apply the hover effect so that the user can understand that the link is clickable & it is not just plain text.

When a new website is designed, the anchor tags are styled with colors matching with the theme. And the same classes of anchor are used across all the pages.

Using the classes for anchor tags also gives a choice to design multiple anchor hover designs & apply them as per the design of a particular region of the page. For example, links used in the footer section can be given different styles & the links in the Navigation bars can be given different styles.

Following is a simple demonstration for the use of Anchor hovers with the help of class.

CSS :-

HTML :-

I am Anchor Tag with Default Style. 
I am Anchor Tag with Hover Effect.

Result :-

CSS section defines hover effect to the anchor class & the effect will be applied only to the anchor with class name & all other anchor elements will work as per their default behavior.

When a user hovers over the link, we are changing the background & text color of the link. Also the styling is displayed in italics. We can apply many other styles & you can give it a try by using some other styles.

We have mentioned the class name anchorHover & applied the styling only to this class. If we remove this class from the CSS section then the hover effect will be applied to all anchor tags.

In the HTML section, we have 2 anchor tags, first one is without class & second one is with class anchorHover . The one without class displays without any hover effect & the second one functions with the given hover effect defined in CSS.

CSS – Button class hover

Button elements are usually used to accept some inputs from the user & they appear at the bottom of all the inputs. User submits the inputs by clicking on the button.

We can see colored buttons in different websites & they enrich the design of the application. The hover effect on the buttons adds an extra layer of enhanced design.

The hover is applied to the button in the same manner as demonstrated in the above examples. Only the elements & classes are replaced before the :hover syntax.

Let’s take a look at the code demonstrating the button hover effect with different colors through CSS.

CSS :-

button < padding: 25px; margin: 25px; font-size: 40px; >button.redStyle:hover < background-color: red; color: white; >button.blueStyle:hover < background-color: blue; color: white; >button.greenStyle:hover < background-color: green; color: white; >button.purpleStyle:hover

HTML :-

    

Result :-

We are defining 4 different classes with different colors in the CSS part of the code. For the purpose of understanding, we have used the same hover effect with different colors.

The first style in CSS is the button style providing normal styling to the buttons like font-size, padding & margins.

The reset of the styles are the hover effects on the buttons with different colors. Any of these classes can be used to apply the hover effect that will change the appearance of the button on hover.

HTML code is populated with 4 buttons having 4 different classes. Each button has been given a different hover effect with the use of classes defined in CSS.

We can see in the Image how the button changes its color on hover. Each button displays a different color because of the particular styles given to it.

Источник

Как добавлять/удалять класс при наведении?

рендерю список с картинками
нужно при onMouseEnter добавлять класс и сохранять его активным до следующего ивента onMouseEnter на другом элементе
а потом удалять у предыдущего и добавлять к текущему
как это сделать?

XanXanXan

Нужно сохранять в состоянии элемент при наведении на него через ( onMouseEnter ).

А в className проверять, совпадает ли этот элемент и тот, что в состоянии. И если совпадает, добавлять ему нужный класс, иначе null .

const [currentActive, setActive] = useState()
Внутри скобок useState указываем элемент, если нужно задать его по умолчанию активным или оставляем их пустыми.

className=
В элементе прописываем выбор класса в зависимости от состояния.

onMouseEnter= setActive(el)>
Меняем состояние при наведении.

XanXanXan

Чипекве, это понятно =) а как его подтянуть то туда ? «первый элемент», как его ввзять то, где ссылка на него?

XanXanXan

Есть же список элементов items

items.map( el => вот какое значение el у первого элемента, такое и нужно передать в useState()

Чипекве, по факту это просто список ссылок которые я тяну из базы, из них я делаю элементы. поэтому нужно получить элемент когда он уже готов после рендера, надо addeventlistener вызывать или ref юзать походу

XanXanXan

useState() сохраняет в currentActive просто значение, в вашем случае ссылку из items.

То есть эта ссылка как бы служит уникальным идентификатором элемента.

Если ссылка на первый элемент заранее неизвестна, можно просто сделать useState(items[0])

Чипекве, фуф. проблема была что функция асинхронная и изначально items были Undefied поборол так что переделал код и переписал в useEffect [items] теперь работает
спасибо )

const [obj, setObj] = useState(null); let classRef = useRef([]); function testfunc(index, e) < if (obj !== null) < classRef.current[obj].classList.remove("img45test"); >e.currentTarget.classList.add("img45test"); setObj(index); >

в итерируемом элементе прописать ref= (classRef.current[index] = el)>
1. пихаем все элементы в useRef
2. далее при первом наведении состояние = Null значит просто добавляем класс и пишем индекс
3. второе наведение с помощью рефа убираем класс у элемента с предыдущем индексом и добавляем к текущему, и опять пишем индекс
4. повторяем по кругу
честно сам не понял как к этому пришел
осталось как то по дефолту сделать сделать элемент с индексом 0 в фокусе со старта

Источник

Читайте также:  Генератор четных чисел питон
Оцените статью