画像を幅いっぱいに表示するボタンを追加するUserScript
code:style.css
.line .image {
width: var(--image-width);
max-width: var(--image-max-width, 99%);
max-height: var(--image-max-height, 300px);
}
スコープを限定
code:script.js
(() => {
変数の初期化
code:script.js
window.IS_IMAGE_EXPANDED = false;
const name = 'toggle image display size';
const expandIcon = 'fas fa-expand';
const compressIcon = 'fas fa-compress';
ボタンを追加
code:script.js
cosense.PageMenu.addMenu({
title: name,
icon: expandIcon,
onClick: () => {
const icon = document.getElementById(name).getElementsByTagName('i')0; const lines = Array.from(document.querySelectorAll('.lines .line'));
const target = findFirstVisibleLine(lines);
const prevTop = target.getBoundingClientRect().top;
if (window.IS_IMAGE_EXPANDED) {
compressImage();
icon.className = expandIcon;
} else {
expandImage();
icon.className = compressIcon;
}
const newTop = target.getBoundingClientRect().top;
window.scrollBy(0, newTop - prevTop);
window.IS_IMAGE_EXPANDED = !window.IS_IMAGE_EXPANDED;
},
});
画像の幅をもとに戻す関数(プロパティを削除)
code:script.js
function compressImage() {
document.documentElement.style.removeProperty('--image-width');
document.documentElement.style.removeProperty('--image-max-width');
document.documentElement.style.removeProperty('--image-max-height');
}
画像の幅を広げる関数(プロパティを設定)
code:script.js
function expandImage() {
document.documentElement.style.setProperty('--image-width', '99%');
document.documentElement.style.setProperty('--image-max-width', 'none');
document.documentElement.style.setProperty('--image-max-height', 'none');
}
見えている行を取得する関数
code:script.js
function findFirstVisibleLine(lines) {
let left = 0;
let right = lines.length - 1;
while (left <= right) {
const mid = Math.floor((left + right) / 2);
const top = linesmid.getBoundingClientRect().top; if (top >= 0) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return result;
}
ページ遷移時に後始末をする
code:script.js
cosense.on('page:changed', compressImage);
スコープを閉じる
code:script.js
})();