本教程操作环境:windows7系统、css3&&html5版、dell g3电脑。
1、使用伪类实现样式切换伪类是css2.1时出现的新特性,让许多原本需要javascript才能做出来的效果使用css就能实现。比如实现下面的鼠标悬停效果,只要为:hover伪类应用一组新样式即可。当访客鼠标移动到按钮上面时,浏览器会自动为按钮应用这新样式。
<!doctype html><html> <head> <meta charset="utf-8"> <style> .slickbutton { color: white; font-weight: bold; padding: 10px; border: solid 1px black; background: lightgreen; cursor: pointer; } .slickbutton:hover { color: black; background: yellow; } </style> </head> <body> <button class="slickbutton">盼望着,盼望着</button> </body></html>
效果:
2、使用css3的过渡功能实现颜色过渡直接使用伪类虽然实现了样式的改变,但由于没有过渡效果会显得很生硬。以前如果要实现过渡,就需要借助第三方的js框架来实现。现在只需要使用css3的过渡(transition)功能,就可以从一组样式平滑的切换到另一组样式。下面鼠标移入后,按钮背景色会慢慢地变成黄色。鼠标离开,过渡效果又会发生,颜色恢复到初始状态。
<!doctype html><html> <head> <meta charset="utf-8"> <style> .slickbutton { color: white; font-weight: bold; padding: 10px; border: solid 1px black; background: lightgreen; cursor: pointer; transition: background 0.5s, color 0.5s; -webkit-transition: background 0.5s, color 0.5s; } .slickbutton:hover { color: black; background: yellow; } </style> </head> <body> <button class="slickbutton">盼望着,盼望着</button> </body></html>
效果:
推荐学习:css视频教程
以上就是css如何实现鼠标经过样式改变的详细内容。
