效果是避免不小心中键点击页签从而关闭文档。
JS 代码片段:
开头有个变量,为 true 时阻止所有页签的中键,为 false 时阻止钉住页签的中键
// 阻止中键关闭任何页签或钉住的页签 JS片段 // author by JeffreyChen https://ld246.com/article/1728321288261 (function() { const applyToAllTabs = true; // 变量:为 true 时阻止所有页签的中键,为 false 时阻止钉住页签的中键 const targetSelector = applyToAllTabs ? '#layouts .layout__center div:not(.fn__none) > .layout-tab-bar:not(.layout-tab-bar--readonly) .item' : '#layouts .layout__center div:not(.fn__none) > .layout-tab-bar:not(.layout-tab-bar--readonly) .item--pin'; const targetContainer = document.querySelector('#layouts'); const observerConfig = { childList: true, subtree: true }; function handleClick(event) { if (event.button !== 1) return; const targetElement = event.target.closest(targetSelector); if (!targetElement) return; event.preventDefault(); event.stopPropagation(); } function attachListener(element) { if (!element.dataset.listenerAttached) { element.addEventListener('mousedown', handleClick, true); element.dataset.listenerAttached = 'true'; } } function detachListener(element) { if (element.dataset.listenerAttached) { element.removeEventListener('mousedown', handleClick, true); delete element.dataset.listenerAttached; } } function checkAndSetupListeners() { const elements = document.querySelectorAll('#layouts .layout__center div:not(.fn__none) > .layout-tab-bar:not(.layout-tab-bar--readonly)'); elements.forEach(attachListener); } const observer = new MutationObserver(mutations => { mutations.forEach(mutation => { // Check for added nodes mutation.addedNodes.forEach(node => { if (node.matches && node.matches('.layout-tab-bar:not(.layout-tab-bar--readonly)')) { attachListener(node); } else if (node.querySelectorAll) { node.querySelectorAll('.layout-tab-bar:not(.layout-tab-bar--readonly)').forEach(attachListener); } }); // Check for removed nodes mutation.removedNodes.forEach(node => { if (node.matches && node.matches('.layout-tab-bar:not(.layout-tab-bar--readonly)')) { detachListener(node); } else if (node.querySelectorAll) { node.querySelectorAll('.layout-tab-bar:not(.layout-tab-bar--readonly)').forEach(detachListener); } }); }); }); observer.observe(targetContainer, observerConfig); // 初始化时设置监听 checkAndSetupListeners(); })();
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于