行にまたがるGradient Underline
この記事は約 5 分で読めます。
CodePenで見つけたアンダーラインを
ご紹介します。
タイトルが気になって翻訳してみました。
【翻訳】
複数の行にまたがるカスタムの
色付きアンダーラインを取得するにはどうすればよいですか?
マウスを重ねてください。
Look At This Pretty Underline
Wow this one is super incredibly cool, and this one is on
Multiple Lines! I wish I had found this like thirty projects
ago when I was representing the lollipop guild.
CodePenでは、SCSSで書かれているので、
CSSに変換し、文字を太字にして、
ホバー時のテキストカラーを
変えたものが以下になります。
.underline_magical {
font-weight: bold;
background-image: linear-gradient(120deg, #84fab0 0%, #8fd3f4 100%);
background-repeat: no-repeat;
background-size: 100% 0.2em;
background-position: 0 88%;
-webkit-transition: background-size 0.25s ease-in;
transition: background-size 0.25s ease-in;
}
.underline_magical:hover {
color: #ffffff;
background-size: 100% 88%;
}
HTMLはこんな感じに書きます。
Look At This <span class="underline_magical">Pretty</span> Underline
基本、CSSだけでもOKですが、
以下のScriptでグラデーションが、
ランダムに変化します。
Babelとありますが、
以下のように普通に
<script></script>で
囲めばよいようです。
<script>
const magicalUnderlines = Array.from(document.querySelectorAll('.underline_magical'));
const gradientAPI = 'https://gist.githubusercontent.com/wking-io/3e116c0e5675c8bcad8b5a6dc6ca5344/raw/4e783ce3ad0bcd98811c6531e40256b8feeb8fc8/gradient.json';
const randNumInRange = max => Math.floor(Math.random() * (max - 1));
const mergeArrays = (arrOne, arrTwo) => arrOne
.map((item, i) => `${item} ${arrTwo[i]}`)
.join(', ');
const addBackground = (elms) => (color) => {
elms.forEach(el => {
el.style.backgroundImage = color;
});
}
const getData = async(url) => {
const response = await fetch(url);
const data = await response.json();
return data.data;
}
const addBackgroundToUnderlines = addBackground(magicalUnderlines);
const buildGradient = (obj) => `linear-gradient(${obj.direction}, ${mergeArrays(obj.colors, obj.positions)})`;
const applyGradient = async(url, callback) => {
const data = await getData(url);
const gradient = buildGradient(data[randNumInRange(data.length)]);
callback(gradient);
}
applyGradient(gradientAPI, addBackgroundToUnderlines);
</script>
See the Pen How do I get a custom colored underline that will span multiple lines? by Will King (@Wking) on CodePen.
constといった記述を
初めてみましたが、
ECMAScript2015から採用された、
新しい宣言の方法だそうです。
貴重なお時間を割き、
最後まで
ご高覧いただきまして
有難うございました
ディスカッション
コメント一覧
まだ、コメントがありません