hover 基本應用
hover 是一種常見的網頁滑鼠互動,用法十分簡單,但是卻可以變化出各種形式。以下筆記幾種常見的用法:
基本用法
HTML元素先設定基本的樣式,再用 選取器:hover{...}
設定滑鼠滑上元素後變化的樣式。
<div class="box"></div>
.box {
width: 100px;
height: 100px;
margin: 100px auto;
transition: 0.5s;
background: #ffa7de;
}
.box:hover {
background: #ffd592;
}
樣式的變換可以是:
- opacity:透明度的變化。
- border-radius:如果要讓正方形的 div 變成圓的,只要設定
:hover{border-radius: 50%}
即可做到。 - transform: 可以讓 HTML 元素放大、縮小、旋轉,範例如下:
.box {
width: 100px;
height: 100px;
margin: 100px auto;
transition: 0.5s;
background: #ffa7de;
}
/* transform 設定 放大1.2倍,旋轉 45 度*/
.box:hover {
transform: scale(1.2) rotate(45deg);
}
hover 結合 keyframes 與 animation
我們來做一個滑鼠移到方塊上,方塊就會搖擺的效果。
.box {
width: 100px;
height: 100px;
margin: 50px auto;
transition: 0.5s;
background: #ffa7de;
}
/* 設定搖擺的過程*/
@keyframes swing {
15% {transform: translateX(5px);}
40% {transform: translateX(-5px);}
65% {transform: translateX(2px);}
85% {transform: translateX(-2px);}
100% {transform: translateX(0px);}
}
/* 把搖擺的過程用 animation 加到 hover 上*/
.box:hover {
animation: swing 1s 1;
}
hover 結合偽元素的應用
一般我們常常看到 navbar 的選項在滑鼠移上去之後,下方會有一條線跑出來。這是利用 ::before
與 ::after
偽元素加上hover所做出來的效果。
div
方塊 position
要設定為 relative
,而 before
與 after
偽元素 position 要設定為 absolute,width 要設定為 0,hover 之後設定為 100%,這樣就會有互動效果產生。
/* 加上 position: relative */
.box {
width: 100px;
height: 100px;
margin: 50px auto;
transition: 0.5s;
background: #ffa7de;
position: relative;
}
/* 設定偽元素的寬度為 0 ,position 為 absolute */
.box:before {
content: "";
width: 0%;
height: 10px;
background-color: #ff5e33;
position: absolute;
top: 0;
left: 0;
transition: all 0.3s linear;
}
.box:after {
content: "";
width: 0%;
height: 10px;
background-color: #ff5e33;
position: absolute;
bottom: 0;
left: 0;
transition: all 0.3s linear;
}
/* 設定偽元素在滑鼠移上去之後,寬度變為 100% */
.box:hover::after {
width: 100%;
}
.box:hover::before {
width: 100%;
}
/* 第二個方塊,滑鼠移上去之後,由下方的中間變出線條 */
.box2 {
width: 100px;
height: 100px;
margin: 50px auto;
transition: 0.5s;
background: #ffa7de;
position: relative;
}
.box2:after {
content: "";
width: 100%;
height: 10px;
background-color: #ff5e33;
position: absolute;
bottom: 0;
left: 0;
transition: transform 0.5s ease;
transform: scaleX(0);
}
.box2:hover::after {
transform: scaleX(1);
}
hover 基本應用
https://popeye-ux.github.io/2023/01/21/hoverBasic/