打开/关闭菜单
打开/关闭外观设置菜单
打开/关闭个人菜单
未登录
未登录用户的IP地址会在进行任意编辑后公开展示。

MediaWiki:Common.js

MediaWiki界面页面
Null留言 | 贡献2025年4月10日 (四) 08:55的版本
(差异) ←上一版本 | 最后版本 (差异) | 下一版本→ (差异)

注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5Ctrl-R(Mac为⌘-R
  • Google Chrome:Ctrl-Shift-R(Mac为⌘-Shift-R
  • Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5
/* 这里的任何JavaScript将为所有用户在每次页面加载时加载。 */

// 获取所有符合条件的图片
//const images = document.querySelectorAll('img[src*="www.guohao.asia"]');

// 遍历图片并调整样式
//images.forEach(img => {
// 获取图片的实际宽度
//    const naturalWidth = img.naturalWidth;

// 根据图片宽度设置样式
//    if (naturalWidth < 600) {
//         img.style.maxWidth = 'none'; // 移除最大宽度限制
//         img.style.width = 'auto';   // 使用图片的实际宽度
//      } else {
//         img.style.width = '80%';    // 宽度大于等于450px时,设置为父容器的80%
//      }
//});


// utils.js (可单独封装)
const debounce = (func, delay) => {
  let timeoutId;
  return (...args) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
};

// 主逻辑
window.addEventListener('load', function() {
  const processImages = () => {
    document.querySelectorAll('img[src*="www.guohao.asia"]').forEach(img => {
      if (!img.complete || img.naturalWidth === 0) return;

      // Retina屏幕适配计算
      const pixelRatio = window.devicePixelRatio || 1;
      const effectiveWidth = img.naturalWidth / pixelRatio;

      // 类名切换逻辑
      img.classList.remove('img-auto', 'img-responsive');
      img.classList.add(effectiveWidth < 600 ? 'img-auto' : 'img-responsive');
    });
  };

  // 防抖处理动态内容
  const debouncedProcess = debounce(processImages, 250);
  
  // 初始执行 + 动态监听
  processImages();
  const observer = new MutationObserver(debouncedProcess);
  observer.observe(document.body, { subtree: true, childList: true });

  // 容错机制:图片加载失败后重试
  document.addEventListener('error', (e) => {
    if (e.target.tagName === 'IMG' && e.target.src.includes('www.guohao.asia')) {
      e.target.src = 'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"></svg>'; // 占位图
      setTimeout(() => processImages(), 1000);
    }
  }, true);
});