やりたいこと
マウスオーバーでリンク文字の色と、画像を差し替える。
→マウスカーソルを合わせる→
最初、画像を<img>タグのsrc属性にセットしていたが、cssからsrcの値を変更できない(;´・ω・){CSS難しい……)
index.html
<span class="test-link"><a href="http://qiita.com"><img src="sample.png">リンク</a></span>
→①<img>タグを使わず、<a>タグの背景画像を使うのかー。
→②::before疑似要素を使う(T_sa様よりコメント頂きました)
実装①
index.html
<span class="test-link"><a href="http://qiita.com">リンク</a></span>
index.css
/* 通常時 */
span.test-link a {
font-size: 30px; /* 文字サイズ */
text-decoration: none; /* リンクの下線を消す */
padding-left: 31px; /* 画像とリンク文字の間隔(余白)を調整 */
color: #AFAFAF; /* 通常時のリンク文字色 */
background: url('sample.png'); /* 通常時の画像 */
background-size: contain; /* 背景のサイズに収まる最大サイズ */
background-repeat: no-repeat; /* 背景画像の繰り返しをしない */
}
/* マウスオーバー時 */
span.test-link a:hover {
font-size: 30px; /* 文字サイズ */
text-decoration: none; /* リンクの下線を消す */
padding-left: 31px; /* 画像とリンク文字の間隔(余白)を調整 */
color: #000000; /* hover時のリンク文字色 */
background: url('hover.png'); /* hover時の画像 */
background-size: contain; /* 背景のサイズに収まる最大サイズ */
background-repeat: no-repeat; /* 背景画像の繰り返しをしない */
}
実装②
index.html
<a href="http://qiita.com">リンク</a>
index.css
/* 通常時 */
a {
font-size: 30px;
text-decoration: none;
padding-left: 31px;
color: #AFAFAF;
}
a::before { /* 通常時の画像を指定 */
content: "";
display: inline-block;
width: 31px;
height: 31px;
background: url('sample.png');
background-size: contain;
background-repeat: no-repeat;
position: relative;
top: 5px;
}
/* マウスオーバー時 */
a:hover {
font-size: 30px;
text-decoration: none;
padding-left: 31px;
color: #000000;
}
a:hover:before { /* マウスオーバー時の画像を指定 */
content: "";
display: inline-block;
width: 31px;
height: 31px;
background: url('hover.png');
background-size: contain;
background-repeat: no-repeat;
position: relative;
top: 5px;
}