search
HomeWeb Front-endCSS TutorialCSS tip: Use transition to retain hover state
CSS tip: Use transition to retain hover stateSep 27, 2022 pm 02:01 PM
csshovertransition

How to retain the hover state? The following article will introduce to you how to retain the hover state without using JavaScript. I hope it will be helpful to you!

CSS tip: Use transition to retain hover state

Normally, hover cannot save the state. Additional styles are triggered when the mouse is moved in, and restored once the mouse is moved out.

el:hover{
  color: red
}

This means that if you need to retain the status of hover, you may have to resort to JS. For example, the following is the ranking effect of the home page of a certain academy

Kapture 2022-09-26 at 18.37.28

The main interactions here are as follows

  • The mouse slides over to trigger the selected state

  • The last selected state will remain after the mouse is moved out of the list (emphasis added)

  • The first item in the default list is selected

The current implementation of the official website is also implemented through JS. In fact, it can be completely achieved only through CSS, and some small delays of transition are required. Let’s take a look at the techniques. [Recommended learning: css video tutorial]

1. The mouse slides over to trigger the selected state

Everything is inseparable from layout.

Assume the listHTML is like this


        
  •       

    将军,夫人喊你种田了

          

    只是在休息室里打了个盹儿,一睁眼,竟然穿成了古代目不识丁的乡下胖丫头。 好吃懒做不说,还在村里横行霸道。 十里八乡没人愿意娶她,好不容易买了个金龟婿,大婚之日竟让人逃了。 恶霸老爹一怒之下去道上掳了个夫君给她。 就是……爹你掳的是不是有点不太对呀? * 婚后的苏胖丫很忙。 忙着改造恶霸爹爹与恶霸弟弟。 忙着抢救貌美如花的神将夫君。 忙着养育三个小小恶霸小豆丁。 一不小心,将自己忙成了大燕最位高权重的一品女侯!

        
  •   
  •       

    被夺一切后她封神回归

          

    【甜爽燃,团宠,玄学】 司扶倾一睁眼,不仅被夺了气运,人人还让她滚出娱乐圈。 重活一次,她只想咸鱼躺,谁知现在圈内人只知拉踩营销,没点真本事,不好好磨炼演技,这样下去还能行?怎么也得收拾收拾。 司扶倾捏了捏手腕,动了。 后来,网上疯狂骂她不自量力倒贴郁曜,造谣她私生活不检点,而—— 国际天后:今天我能站在这里,多亏了倾倾 top1男顶流:离我妹妹远点@郁曜 就连国际运动会官方:恭喜司扶倾拿下第13枚个人金牌,等一个退圈 当天,全网瘫痪。 · 史书记载,胤皇年少成名,八方征战,平天下,安宇内,是大夏朝最年轻的帝王,他完美强大,心怀天下,却因病死于27岁,一生短暂,无妻无妾,无子无孙,是无数人的白月光男神。 无人知晓,他再睁开眼,来到了1500年后。 这一次,他看见了他遥想过的盛世大夏。 · 不久后胤皇身份曝光,司扶倾得知偶像竟然就在身边,她敬佩万分,只想—— 司扶倾:努力奋斗,报效大夏! 胤皇:以身相许 司扶倾:??? 我一心奋发上进你却想要我? · 全能颜巅女神×杀伐清贵帝王 从全网黑到封神顶流,顺便和男神1v1

        
  •   ...

Simple modification

.list{
  list-style: none;
  margin: 0;
  padding: 0;
  width: 400px;
}
.item{
  position: relative;
  padding: 10px 10px 10px 34px;
  cursor: pointer;
  counter-increment: num;
}
.title::before{
  content: counter(num) ' ';
  width: 25px;
  line-height: 30px;
  text-align: center;
  color: #fff;
  position: absolute;
  font-size: 14px;
  font-family: fantasy;
  left: 4px;
  background: center/100% 100% url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADQAAAA8CAMAAAAe9Wm0AAAAbFBMVEUAAACaov2SnPKXnvaXofiyuvuCjPOgqvi4vfiBjPSyuf6Ml/a0u/21vPtte/F/i/WTnfWNmPiyuv6Ik/Zue/GRnPinr/Wfp/Gyuv6Ml/ebo/KTnfOutfqEj/W3vvpue/G/xfd1gvN8iPRodfBFzp+BAAAAF3RSTlMAECA7U2BgdIiTn6Wsvr+/v9Df39/s/o6+GugAAAGPSURBVHjazdZhk4IgEAZgpS6z8iotPEBF8P//x1tJrTxQlrm5uff7MxubLBtF9sQfp+ywjRCJk+zLhPq6SUwuxokhp4/YT1SUVtWam4nSZObImyA2YXHZ022cYsirOzwYoYti7nJzuMOqeHPNvke5jxgP2DRNNqLSMzQQtXjUtv8cBTWiwqOqohcsKikt8ajkHI+4EGjEBWNnNGJ1jUe1Vp9YJLSSeKRkh0eyC0BdEJIBZ5J/h1TA/6SUOgcgjUdaT6gJQA0CjV85jFrq/ZU/UYtA7HFzG5iA1PcOMnbs0b7tU/mcCAhjO/NE52A8jmXKMHYdnukTzE141vhyGWaSTq97ksMQhOnEF8qYFJvXneDO++lU82VznG0giYDppBVzTTvIffdjZSGFVjA2JHeVuRDbopOC6TrJ7GUSx0a1vYGR8u1kQ5krce5hJAUjlRbuRtuyu8GFVopxZ6OtxW5wObU2P3Ewaby+jya6R7UYO+C3xpICbk3NFhptTToaZ6OtzS/WGm39iUdkmdFFv5pvdNPREWjicTcAAAAASUVORK5CYII=);
}
.title{
  margin: 0;
  padding: 8px 0;
  font-weight: normal;
}
.sumary{
  margin: 0;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  color: #666;
  font-size: 14px;
  color: 20px;
  height: 0;
}

.item::before{
  content: '';
  position: absolute;
  inset: 0;
  border-radius: 8px;
  opacity: 0;
  z-index: -1;
  background: linear-gradient(270deg, rgb(241, 236, 249) 0%, rgba(241, 236, 249, 0) 100%);
}

The effect is as follows

CSS tip: Use transition to retain hover state

Now add the effect of hover

.item:hover .title{
  color: rebeccapurple;
}
.item:hover .sumary{
  height: 40px;
}
.item.item:hover::before{
  opacity: 1;
}

The effect is as follows

Kapture 2022-09-17 at 13.12.45

##Very normal

hover effect, Nothing special, so how to retain the last state after moving out? Then read on

2. Retain the status of

hover

You need to use such a little trick to achieve

hover retention status.

For example, add a

hover style to an element

el:hover{
  color: red
}

Kapture 2022-09-17 at 13.18.58

If we add a delay to this element

el{
  transition-delay: 1s;
}
Then, there will be a delay when the mouse moves in and out

Kapture 2022-09-17 at 13.20.43

Then, we cancel the delay when

hover

el:hover{
  color: red;
  transition-delay: 0s;
}
Then, the mouse will respond quickly when moving in, and there will still be a delay when moving out.

Kapture 2022-09-17 at 13.24.09

I believe everyone understands this, if the delay is set to enough Large, such as

el{
  transition-delay: 9999s;
}
, after the mouse is moved out, it needs to go through

9999s before it changes to its original state, which is equivalent to retaining the hover state

Kapture 2022-09-17 at 13.28.42

The principle is like this, let’s take a look at the actual application

3. After the mouse is moved out of the list, the last selected state will still be retained

According to the above Principle, we can easily achieve retaining the state after

hover, as follows

/* 默认 transition */
.item::before,
.item .sumary,
.item .title{
  transition: 0s 9999s;
}
/* 每一项hover */
.item:hover .title{
  color: rebeccapurple;
  transition: none;
}
.item:hover .sumary{
  height: 40px;
  transition: none;
}
.item.item:hover::before{
  opacity: 1;
  transition: none;
}
It should be noted that since it is

transition, so all state changes All need to support transition attributes , such as hiding sumary here is height: 0 instead of display:none, and the selected background Color change, because background-image does not support transition, so I changed it to ::before, and then used opacity alone to control some details, etc. The effect is as follows

Kapture 2022-09-26 at 20.02.53

In this way, after the mouse leaves, the previous state is still retained. But we only need to keep the last one, not all of them. How to deal with it?

这里需要换一种思路,可以这么做,鼠标在移入整个列表的时候就清除所有的状态,这样就只有当前hover的选项才会保留下来,有点类似于JS中的思维,先把所有的.current都移除,再给当前项添加.current,实现如下

/* 清除所有hover */
.list:hover .title{
  transition: none;
  color: #333;
}
.list:hover .sumary{
  transition: none;
  height: 0;
}
.list:hover .item::before{
  transition: none;
  opacity: 0;
}

这样就实现了鼠标移出列表后仍然保留上一次的选中态的功能,有点像单选框的效果,只不过是hover触发的,效果如下

Kapture 2022-09-17 at 13.54.53

四、默认列表的第一项为选中态

下面来实现最后一个功能。

这个相对而言比较容易,需要用到:first-child伪类,可以匹配到第一个元素。

不过需要考虑的是优先级的问题,这个是默认状态,权限应该是最低的,其他hover样式都应该可以覆盖它,所以可以放在最前面,如下

/* 初始状态(第一个选中) */
.item:first-child .sumary{
  height: 40px;
}
.item:first-child .title{
  color: rebeccapurple;
}
.item:first-child::before{
  opacity: 1;
}

/* 清除所有hover */

/* 每一项hover */

这样就完美实现了文章开头的效果

Kapture 2022-09-17 at 14.04.17

由于是 CSS 实现,多个列表也是完全复用的

Kapture 2022-09-26 at 20.22.33.gif

完整代码可以查看线上 demo:CSS keep hover(runjs.work)

五、总结一下

以上就是通过纯 CSS 实现保留鼠标滑过样式的全部技巧了,主要还是对transition-delay的灵活运用,下面总结一下

  • 实现原理的利用transition-delay,让“还原”的时间足够长,这样就实现了保留hover状态的效果了

  • 单选效果可以在鼠标移入整个列表的时候就清除所有的状态,这样就只有当前hover的选项才会保留下来,有点类似于JS中的思维

  • 需要注意所有属性必须是支持transition的,比如display:none就不支持transition,需要用其他样式代替

当然,整个实现对于 CSS 以及选择器要求是相当高的,实际项目过程中可能并不如 JS 实现来的快,但是,CSS能够实现的又何必动用 JS呢?在我看来,JS就应该回归本职,专心处理数据逻辑交互,视觉方面全部交给CSS就行了,只是现在CSS还不够强大,实现需要用到很多奇技淫巧,但是,CSS现在已经在变得足够强大,比如:has伪类,相信未来CSS会越来越美好

(学习视频分享:css视频教程web前端

The above is the detailed content of CSS tip: Use transition to retain hover state. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
利用CSS怎么创建渐变色边框?5种方法分享利用CSS怎么创建渐变色边框?5种方法分享Oct 13, 2021 am 10:19 AM

利用CSS怎么创建渐变色边框?下面本篇文章给大家分享CSS实现渐变色边框的5种方法,希望对大家有所帮助!

css ul标签怎么去掉圆点css ul标签怎么去掉圆点Apr 25, 2022 pm 05:55 PM

在css中,可用list-style-type属性来去掉ul的圆点标记,语法为“ul{list-style-type:none}”;list-style-type属性可设置列表项标记的类型,当值为“none”可不定义标记,也可去除已有标记。

css与xml的区别是什么css与xml的区别是什么Apr 24, 2022 am 11:21 AM

区别是:css是层叠样式表单,是将样式信息与网页内容分离的一种标记语言,主要用来设计网页的样式,还可以对网页各元素进行格式化;xml是可扩展标记语言,是一种数据存储语言,用于使用简单的标记描述数据,将文档分成许多部件并对这些部件加以标识。

css3怎么实现鼠标隐藏效果css3怎么实现鼠标隐藏效果Apr 27, 2022 pm 05:20 PM

在css中,可以利用cursor属性实现鼠标隐藏效果,该属性用于定义鼠标指针放在一个元素边界范围内时所用的光标形状,当属性值设置为none时,就可以实现鼠标隐藏效果,语法为“元素{cursor:none}”。

css怎么设置i不是斜体css怎么设置i不是斜体Apr 20, 2022 am 10:36 AM

在css中,可以利用“font-style”属性设置i元素不是斜体样式,该属性用于指定文本的字体样式,当属性值设置为“normal”时,会显示元素的标准字体样式,语法为“i元素{font-style:normal}”。

rtl在css是什么意思rtl在css是什么意思Apr 24, 2022 am 11:07 AM

在css中,rtl是“right-to-left”的缩写,是从右往左的意思,指的是内联内容从右往左依次排布,是direction属性的一个属性值;该属性规定了文本的方向和书写方向,语法为“元素{direction:rtl}”。

css怎么实现英文小写转为大写css怎么实现英文小写转为大写Apr 25, 2022 pm 06:35 PM

转换方法:1、给英文元素添加“text-transform: uppercase;”样式,可将所有的英文字母都变成大写;2、给英文元素添加“text-transform:capitalize;”样式,可将英文文本中每个单词的首字母变为大写。

怎么设置rotate在css3的旋转中心点怎么设置rotate在css3的旋转中心点Apr 24, 2022 am 10:50 AM

在css3中,可以用“transform-origin”属性设置rotate的旋转中心点,该属性可更改转换元素的位置,第一个参数设置x轴的旋转位置,第二个参数设置y轴旋转位置,语法为“transform-origin:x轴位置 y轴位置”。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.