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

仅使用Vanilla JavaScript创建带可执行按钮的可切换书签菜单问询

纯JavaScript书签工具菜单实现方案

直接上可运行的实现代码,分为便于理解的未压缩版和适合书签使用的压缩版:

未压缩版代码(用于调试与理解逻辑)

(function() {
  // 创建菜单容器
  const menu = document.createElement('div');
  // 通过JS内置样式属性替代CSS
  menu.style.position = 'fixed';
  menu.style.top = '20px';
  menu.style.right = '20px';
  menu.style.background = '#fff';
  menu.style.border = '1px solid #ccc';
  menu.style.padding = '10px';
  menu.style.zIndex = '99999';
  menu.style.boxShadow = '0 2px 8px rgba(0,0,0,0.15)';

  // 创建关闭按钮
  const closeBtn = document.createElement('button');
  closeBtn.textContent = '关闭';
  closeBtn.style.width = '100%';
  closeBtn.style.marginBottom = '10px';
  closeBtn.addEventListener('click', () => {
    document.body.removeChild(menu);
  });
  menu.appendChild(closeBtn);

  // 定义菜单按钮及对应执行的代码
  const menuItems = [
    {
      text: '控制台输出Hello',
      action: () => {
        console.log('Hello from Bookmarklet Menu!');
      }
    },
    {
      text: '修改页面标题',
      action: () => {
        document.title = '被书签工具修改了!';
      }
    },
    {
      text: '隐藏所有图片',
      action: () => {
        document.querySelectorAll('img').forEach(img => img.style.display = 'none');
      }
    }
  ];

  // 批量生成功能按钮
  menuItems.forEach(item => {
    const btn = document.createElement('button');
    btn.textContent = item.text;
    btn.style.width = '100%';
    btn.style.marginBottom = '8px';
    btn.addEventListener('click', () => {
      item.action();
    });
    menu.appendChild(btn);
  });

  // 将菜单挂载到页面
  document.body.appendChild(menu);
})();

压缩版(直接复制到书签地址栏使用)

javascript:(function(){const e=document.createElement("div");e.style.position="fixed",e.style.top="20px",e.style.right="20px",e.style.background="#fff",e.style.border="1px solid #ccc",e.style.padding="10px",e.style.zIndex="99999",e.style.boxShadow="0 2px 8px rgba(0,0,0,0.15)";const t=document.createElement("button");t.textContent="关闭",t.style.width="100%",t.style.marginBottom="10px",t.addEventListener("click",()=>{document.body.removeChild(e)}),e.appendChild(t);const n=[{text:"控制台输出Hello",action:()=>{console.log("Hello from Bookmarklet Menu!")}},{text:"修改页面标题",action:()=>{document.title="被书签工具修改了!"}},{text:"隐藏所有图片",action:()=>{document.querySelectorAll("img").forEach(e=>e.style.display="none")}}];n.forEach(t=>{const n=document.createElement("button");n.textContent=t.text,n.style.width="100%",n.style.marginBottom="8px",n.addEventListener("click",()=>{t.action()}),e.appendChild(n)}),document.body.appendChild(e)})();

核心注意事项

  • 书签工具必须以javascript:开头,这是浏览器识别书签脚本的强制标识
  • 所有代码封装在自执行函数内,避免污染全局变量,防止和页面原有JS冲突
  • 完全通过element.style设置样式,不依赖外部CSS文件
  • 无需监听页面加载事件,因为书签工具是在页面加载完成后触发执行的
  • 扩展功能只需修改menuItems数组里的action函数,可实现任意JS逻辑(DOM操作、数据请求等)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:42:52