我正在浏览一个有嵌入图片的嘉宾论坛。默认情况下,网站对未登录用户的图片进行模糊处理。
查看HTML,我发现我可以将以下span的类更改为空:
<span class="attachmentPreview">
<span class="">
为了解除图片的模糊。
我有非常基本的JavaScript知识,但足以将我的第一个扩展加载到Firefox中,并确保它只运行在特定的URL上(在本例中是论坛)。
我的问题:
如何与特定元素交互(span class="attachmentPreview"?)以修改它以更新为?
它需要发生在去,作为论坛动态模糊的图片,因为用户向下滚动帖子之间:我如何确保我的脚本不断检查网站上的任何新图片?
多谢
我能够找到元素document.getElementsByClassName("attachmentPreview")
只需注入一个覆盖该规则的样式表,或者添加一个允许您为站点添加自定义样式的扩展。
document.head.insertAdjacentHTML("beforeend", `<style>.attachmentPreview { filter: none !important; }</style>`)
.attachmentPreview { filter: blur(1.5rem); }
<span class="attachmentPreview">
<img src="http://placekitten.com/200/300" />
</span>
下面是一个使用MutationObserver
的例子:
const main = () => {
// When the page has been scrolled 100%
// See: https://stackoverflow.com/a/75266945/1762224
window.addEventListener('scrollend', loadImage);
// Remove pre-loaded
document.querySelectorAll('.attachmentPreview').forEach(removeBlur);
// Remove dynamic
observe('.attachmentPreview', removeBlur, document.body);
};
// Source: https://stackoverflow.com/a/65585776/1762224
const observe = (selector, callback, targetNode = document.body) =>
new MutationObserver(mutations => [...mutations]
.flatMap((mutation) => [...mutation.addedNodes])
.filter((node) => node.matches && node.matches(selector))
.forEach(callback))
.observe(targetNode, { childList: true, subtree: true });
const loadImage = () => {
const span = document.createElement('span');
const img = document.createElement('img');
img.src = 'http://placekitten.com/260/120';
span.classList.add('attachmentPreview');
span.append(img);
document.body.append(span);
};
// Timeout is just for demonstration.
const removeBlur = (span) => {
console.log('Removing blur in 1 second...');
setTimeout(() => {
span.classList.remove('attachmentPreview');
}, 1000);
};
main();
body {
text-align: center;
}
body>span {
display: block;
}
.attachmentPreview {
filter: blur(0.667rem);
}
<script src="https://cdn.jsdelivr.net/gh/argyleink/scrollyfills/dist/scrollyfills.umd.js"></script>
<span class="attachmentPreview">
<img src="http://placekitten.com/260/120" />
</span>
<span class="attachmentPreview">
<img src="http://placekitten.com/260/120" />
</span>
<span class="attachmentPreview">
<img src="http://placekitten.com/260/120" />
</span>
<span class="attachmentPreview">
<img src="http://placekitten.com/260/120" />
</span>