italia2024
Version:
Italia 2024 assets
44 lines (36 loc) • 1.32 kB
JavaScript
(function () {
//_insert-anchorStyle.js
//[anchor] 属性を持つすべての要素を取得
const elements = document.querySelectorAll('[anchor]');
//スタイル要素を作成(一度だけ作成)
const STYLE = document.createElement('style');
document.head.appendChild(STYLE);
elements.forEach((el) => {
//anchor 属性から値を取得
const anchorValue = el.getAttribute('anchor');
//値と単位を分離する正規表現('r'も含める)
const match = anchorValue.match(/^(\d*\.?\d+)(px|pc|r|rem|vw)?$/);
if (match) {
const value = parseFloat(match[1]);
let unit = match[2] || 'px'; //単位が指定されていない場合はpxとする
//'r' を 'rem' に変換
if (unit === 'r') {
unit = 'rem';
}
//要素のidを取得
const id = el.id;
//CSSルールを生成
const anchorStyle = `
#${id} {
margin-top: -${value}${unit};
padding-top: ${value}${unit};
}
`;
//スタイルに追加
STYLE.sheet.insertRule(anchorStyle, STYLE.sheet.cssRules.length);
} else {
//マッチしない場合(数値・単位でない場合)は何もしない
console.log(`Skipping invalid anchor value for element with id "${el.id}": ${anchorValue}`);
}
});
})();