You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使图片固定在页面左上角?书签工具代码调试求助

解决书签工具图片固定左上角且不拉伸的问题

原代码直接将图片追加到body末尾,没有定位规则导致图片显示在页面底部,同时固定宽高会强制拉伸图片。按以下方式修改代码,可实现类似导航栏的固定效果:

function display_image(src, maxWidth, maxHeight, alt) {
  var img = document.createElement("img");
  img.src = src;
  img.alt = alt;
  // 设置核心样式:固定位置、保持比例、层级置顶
  img.style.position = "fixed";
  img.style.top = "0";
  img.style.left = "0";
  img.style.zIndex = "9999";
  img.style.objectFit = "contain";
  img.style.maxWidth = `${maxWidth}px`;
  img.style.maxHeight = `${maxHeight}px`;
  // 可选:若不需要图片响应点击,取消注释下面一行,避免遮挡页面其他元素交互
  // img.style.pointerEvents = "none";
  document.body.appendChild(img);
}

display_image('https://raw.githubusercontent.com/mrmojololo/nokokaiwa/main/musicplayer.png', 276, 110, 'imagejs');

关键修改说明:

  • 替换固定width/height为maxWidth/maxHeight,配合objectFit: contain,既限制图片最大显示尺寸,又严格保留图片原始比例,避免拉伸变形。
  • 添加position: fixed+top:0+left:0,让图片固定在页面左上角,不会随页面滚动位移。
  • 设置zIndex: 9999,确保图片始终显示在所有页面内容上方,不会被其他元素遮挡。

内容的提问来源于stack exchange,提问作者mojoishere

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:40:31