アイコン付き吹き出しをJavaScriptとCSSで作る
こんなアイコン付き吹き出しを作ってみたよ♪
WordPressみたいなアイコン付きの吹き出しを記事に簡単に挿入できないものかと、別になくても良いけどw普段あまり使わない aside と figure タグを使ってできそうなので作ってみました。
CSS
/* 吹き出し */
/* 共通 */
aside, figure {
max-width: 60%;
margin: 12px 0;
font-family: sans-serif;
font-size: 1rem;
color: #111;
background: linear-gradient(135deg, #ffe, #ff9);
display: inline-block;
display: flex;
align-items: flex-start;
gap: 10px;
margin: 10px 0;
border: 1px solid #ccc; /* 枠線 */
border-radius: 16px; /* 角丸 */
padding: 12px 18px; /* 中の文章との余白 */
position: relative; /* 三角やアイコン位置維持用 */
flex-wrap: wrap; /* ←折り返し許可 */
}
/* 左吹き出し (aside) */
aside {
float: left;
clear: both;
margin-left: 80px; /* アイコン分の余白 */
}
aside::before {
content: "";
position: absolute;
left: -90px; /* 吹き出しの外へ */
top: 0;
width: 80px;
height: 80px;
border-radius: 50%;
background-image: var(--icon-url);
background-size: cover;
background-position: center;
}
aside::after {
content: '';
position: absolute;
top: 50%; /* 垂直方向の位置 */
left: -16px; /* 吹き出し左端の外側 */
transform: translateY(-50%); /* 真ん中に合わせる */
border: 8px solid transparent; /* 三角の形を作る */
border-right-color: #f79; /* 向きと色を決める */
}
/* 右吹き出し (figure) */
figure {
float: right;
clear: both;
margin-right: 80px; /* アイコン分の余白 */
justify-content: flex-end;
}
figure::before {
content: "";
position: absolute;
right: -90px; /* 吹き出しの外へ */
top: 0;
width: 80px;
height: 80px;
border-radius: 50%;
background-image: var(--icon-url);
background-size: cover;
background-position: center;
}
figure::after {
content: '';
position: absolute;
top: 50%;
right: -16px;
transform: translateY(-50%);
border: 8px solid transparent;
border-left-color: #888;
}
JavaScript
// 吹き出し
(function() {
// 左吹き出し用アイコンアドレス
const iconsAside = [
"https://********************/*********.png",// data-icon='0'
"https://********************/*********.png",// 1
"https://********************/*********.png" // 2
];
// 右吹き出し用アイコンアドレス
const iconsFigure = [
"https://********************/*********.png",// data-icon='0'
"https://********************/*********.png",// 1
"https://********************/*********.png" // 2
];
// 共通関数
function applyIcons(selector, icons) {
document.querySelectorAll(selector).forEach(el => {
const index = parseInt(el.dataset.icon, 10) || 0;
if (icons[index]) {
el.style.setProperty("--icon-url", `url('${icons[index]}')`);
}
});
}
// 適用
applyIcons('[id*="post-body-"] aside', iconsAside);
applyIcons('[id*="post-body-"] figure', iconsFigure);
})();
使用法
<aside data-icon="1">吹き出し左</aside>
<figure data-icon="0">右吹き出し</figure>
このように書けば表示されます。アイコン画像はいくつでも追加可能。data-icon未記入 or 数値未入力 の場合は[0]が適用されます。
コメント
コメントを投稿