Greasy Fork

来自缓存

Greasy Fork is available in English.

搜索美化: 百度/Bing去广告、自动翻页、界面美化、宽屏单列

顶部工具栏毛玻璃效果、底部分页栏悬浮、搜索结果添加边框、搜索结果宽屏单列显示、隐藏工具栏、隐藏分页并自动加载下一页、鼠标悬停渐变光层效果。支持百度、Bing两大搜索引擎

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @license MIT
// @name         搜索美化: 百度/Bing去广告、自动翻页、界面美化、宽屏单列
// @name:zh-CN   搜索美化: 百度/Bing去广告、自动翻页、界面美化、宽屏单列
// @namespace    search_beautify
// @version      7.98
// @description  顶部工具栏毛玻璃效果、底部分页栏悬浮、搜索结果添加边框、搜索结果宽屏单列显示、隐藏工具栏、隐藏分页并自动加载下一页、鼠标悬停渐变光层效果。支持百度、Bing两大搜索引擎
// @description:zh-CN 顶部工具栏毛玻璃效果、底部分页栏悬浮、搜索结果添加边框、搜索结果宽屏单列显示、隐藏工具栏、隐藏分页并自动加载下一页、鼠标悬停渐变光层效果。支持百度、Bing两大搜索引擎
// @author       豆沙包里加辣椒
// @run-at       document-start
// @match        https://www.baidu.com/*
// @match        https://www.bing.com/*
// @match        https://cn.bing.com/*
// @match        https://*.bing.com/*
// @grant        GM_addStyle
// @grant        GM_setValue
// @grant        GM_getValue
// ==/UserScript==

/**
 * 修改指定DOM
 * @param domSelector DOM选择器
 * @param style 样式
 */
function modifyDOM(domSelector, style){
    GM_addStyle( domSelector + '{' + style + '}' );
}

/**
 * 隐藏指定DOM
 * @param domSelector DOM选择器
 */
function hideDOM(domSelector){
    GM_addStyle( domSelector + '{display: none !important;}' );
}

/**
 * 判断DOM包含类
 * @param domSelector DOM选择器
 * @param className 类名
 */
function containDOMClass(domSelector, className){
    const dom = getDOM(domSelector);
    if(dom) {
        return dom.classList.contains(className);
    } else {
        return false;
    }
}

/**
 * 替换DOM类
 * @param domSelector DOM选择器
 * @param className 类名
 */
function replaceDOMClass(domSelector, oldClassName, newClassName){
    const dom = getDOMs(domSelector);
    getDOMs(domSelector).forEach(function(r){
        r.classList.add(newClassName);
        r.classList.remove(oldClassName);
    });
}

/**
 * 获取单个DOM
 * @param domSelector DOM选择器
 * @returns DOM
 */
function getDOM(domSelector, retryTime) {
    return document.querySelector(domSelector);
}

/**
 * 获取多个DOM
 * @param domSelector DOM选择器
 * @returns DOMs
 */
function getDOMs(domSelector) {
    return document.querySelectorAll(domSelector);
}

/**
 * 删除多个DOM
 * @param domSelector DOM选择器
 */
function deleteDOMs(domSelector) {
    getDOMs(domSelector).forEach(function(r){
        r.remove();
    });
}

/**
 * 移动DOM
 * @param srcDomSelector 来源DOM选择器
 * @param dstDomSelector 目标DOM选择器
 */
function moveBeforeDOM(srcDomSelector, dstDomSelector) {
    const srcDom = getDOM(srcDomSelector);
    const dstDom = getDOM(dstDomSelector);
    if(srcDom != null && dstDom != null) {
        dstDom.before(srcDom);
    }
}

/**
 * 检测当前搜索引擎
 * @returns {string|null} 'baidu', 'bing' 或 null
 */
function getSearchEngine() {
    const host = window.location.hostname.toLowerCase();
    if (host.includes('baidu.com')) return 'baidu';
    if (host.includes('bing.com')) return 'bing';
    return null;
}

/**
 * 生成回到顶部按钮
 */
function generateScrollToTopElement(){
    const tmpDivA = document.createElement("div");
    tmpDivA.id = 'scrollToTopA';
    tmpDivA.classList.add('scrollToTop');
    tmpDivA.style = 'position: fixed; bottom: 80px; border-radius: 50%; cursor: pointer; height: 44px; width: 44px; align-items: center; justify-content: center; box-shadow: 0 2px 4px 0 rgba(0,0,0,.05); background: #fff; right: 50px; z-index: 1000;';
    tmpDivA.innerHTML = '';
    tmpDivA.onclick = function() {
        window.scrollTo({ left: 0, top: 0, behavior: 'smooth' });
    };
    getDOM('html').appendChild(tmpDivA);
    replaceDOMClass('.scrollToTop', 'show', 'hide');
    // 通用回到顶部按钮样式
    GM_addStyle(
        '#scrollToTopA{right: 50px}' +
        '.scrollToTop.show{display: flex}' +
        '.scrollToTop.hide{display: none}'
    );
}

/**
 * 显示提示信息
 */
function showToast(msg){
    deleteDOMs('#pageLoaded');
    var m = document.createElement('div');
    m.id = 'pageLoaded';
    m.innerHTML = msg;
    m.style = "padding:0 14px; height: 40px; color: white; line-height: 40px; text-align: center; border-radius: 10px; position: fixed; bottom: 5%; left: 50%; transform: translate(-50%, -50%); z-index: 9999; background: rgba(0, 0, 0, 0.7); font-size: 16px;";
    document.body.appendChild(m);
    setTimeout(function() {
        var d = 0.5;
        m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
        m.style.opacity = '0';
    }, 500);
}

/**
 * 获取URL参数
 */
function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

/**
 * 强制居中布局(用JS直接操作DOM,优先级最高)
 */
function forceCenterLayout() {
    const wrapper = document.querySelector('#wrapper');
    const container = document.querySelector('#container');
    const contentLeft = document.querySelector('#content_left');
    
    if (!container) return;
    
    // 计算容器宽度:92vw,最大1400px
    const viewportWidth = window.innerWidth;
    let containerWidth = Math.min(viewportWidth * 0.92, 1400);
    containerWidth = Math.max(containerWidth, 600); // 最小600px
    
    // 强制设置wrapper
    if (wrapper) {
        wrapper.style.cssText = `
            width: 100% !important;
            display: block !important;
            float: none !important;
            position: relative !important;
            left: auto !important;
            transform: none !important;
        `;
    }
    
    // 强制设置container居中
    container.style.cssText = `
        width: ${containerWidth}px !important;
        margin: 0 auto !important;
        padding: 0 24px !important;
        box-sizing: border-box !important;
        float: none !important;
        position: relative !important;
        left: auto !important;
        right: auto !important;
        transform: none !important;
    `;
    
    // 强制设置content_left
    if (contentLeft) {
        contentLeft.style.cssText = `
            width: 100% !important;
            float: none !important;
            margin: 0 !important;
            padding: 0 !important;
        `;
    }
    
    console.log('[搜索美化] 强制居中完成,容器宽度:', containerWidth, 'px');
}

/**
 * 主初始化函数
 */
function init() {
    const engine = getSearchEngine();
    if (engine === 'baidu') {
        initBaidu();
    } else if (engine === 'bing') {
        initBing();
    }
    // 通用的回到顶部按钮
    generateScrollToTopElement();
}

// ==================== 百度搜索初始化 ====================
function initBaidu() {
    // 增强页面立体效果 - 渐变背景
    GM_addStyle(
        'body{background: linear-gradient(180deg, #f0f2f5 0%, #ffffff 100%) !important;}'
    );
    
    // 搜索框区域居中显示
    modifyDOM('#head', 'background-color: rgba(248,248,248,0.4)');
    modifyDOM('.head_wrapper', 'width: 90%; max-width: 1200px; margin: 0 auto;');
    modifyDOM('.s_form', 'backdrop-filter: blur(10px); width: 100%;');
    modifyDOM('.s_form_wrapper', 'width: 100%; display: flex; justify-content: center');
    modifyDOM('#form', 'width: 100%; max-width: 800px; margin: 0 auto');
    hideDOM('[tpl="app/search-tag"]');

    // 工具栏样式, 透明效果
    modifyDOM('#s_tab', 'height: 11px; border-bottom: #e0e0e0 1px solid; background-color: rgba(248,248,248,0.4) !important; overflow: hidden;')
    modifyDOM('.s_tab_inner', 'background-color: rgba(248,248,248,0.4)');

    // 去除右侧
    hideDOM('#content_right');
    
    // ==================== 宽屏单列布局(CSS先行 + JS强制)====================
    // 核心思路:CSS先做基础居中避免闪烁,JS再强制精确控制
    
    // 第一步:CSS立即注入基础居中样式(避免先居左再居中)
    GM_addStyle(`
        /* 基础居中 - 防止闪烁 */
        #wrapper {
            width: 100% !important;
        }
        #container {
            width: min(92vw, 1400px) !important;
            margin: 0 auto !important;
            padding: 0 24px !important;
            box-sizing: border-box !important;
        }
        #content_left {
            width: 100% !important;
            float: none !important;
        }
        #content_left > div,
        #content_left > table {
            width: 100% !important;
        }
    `);
    
    // 搜索框居中修复
    GM_addStyle(`
        /* 顶部整体居中 */
        .head_wrapper {
            width: 100% !important;
            display: flex !important;
            justify-content: center !important;
        }
        
        /* 搜索框限制宽度 */
        #form {
            width: 100% !important;
            max-width: 700px !important;
            margin: 0 auto !important;
        }
    `);
    
    // 第二步:JS立即执行强制居中(用requestAnimationFrame确保DOM存在)
    function tryForceCenter() {
        if (document.querySelector('#container')) {
            forceCenterLayout();
        } else {
            requestAnimationFrame(tryForceCenter);
        }
    }
    
    // 尝试立即执行,如果DOM没准备好就等待
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', forceCenterLayout);
    } else {
        requestAnimationFrame(tryForceCenter);
    }
    
    // 监听窗口大小变化
    window.addEventListener('resize', function() {
        clearTimeout(window.resizeTimer);
        window.resizeTimer = setTimeout(forceCenterLayout, 50);
    });

    GM_addStyle(
        '.new-pmd .c-span8{width: calc(100% - 192px) !important}' +
        '.new-pmd .c-span9{width: calc(100% - 144px) !important}' +
        '.new-pmd .c-span12{width: 100% !important}' +
        // 内容卡美化
        '#content_left>div{background: #f5e4ea !important; margin-right:0 !important;margin-bottom:20px !important;border-radius:12px !important;padding:16px !important;-webkit-box-shadow: 0 2px 5px 0 rgba(0,0,0,.1) !important;}' +
        '#content_left>table{margin-right:0 !important;margin-bottom:20px !important;border-radius:12px !important;-webkit-box-shadow: 0 2px 5px 0 rgba(0,0,0,.1) !important;}' +
        '#content_left>table>tbody>tr>td{padding:16px !important}' +
        '#content_left>table>tbody>tr>td>div{width:560px !important;-webkit-box-shadow:unset !important;border: none !important;padding: 0 !important}' +
        '.c-border{-webkit-box-shadow:unset !important;margin-bottom: 0 !important;border: none !important}' +
        '[class*="single-card-wrapper"] {margin: -46px -16px -16px; padding: 46px 16px 10px 16px !important; box-shadow: unset !important}' +
        '[class*=content-border] {box-shadow: unset !important}' +
        '.wd-ai-index-pc {margin: -16px !important; width: unset !important}' +
        '.new-pmd.c-container {width: fit-content !important}' +
        // 隐藏相关搜索&其他人在搜
        '#rs_new, [tpl=recommend_list], [tpl=app\\/footer], div[data-click="{"]{display: none !important}' +
        // 隐藏分页栏(使用自动翻页)
        '#page{display: none !important; visibility: hidden !important; height: 0 !important;}' +
        // 鼠标悬停渐变光层效果
        '#content_left>div{position: relative; overflow: hidden;}' +
        '#content_left>div::before{content: ""; position: absolute; top: 0; left: -100%; width: 100%; height: 100%; background: linear-gradient(90deg, transparent, rgba(0, 255, 255, 0.15), rgba(138, 43, 226, 0.12), transparent); transition: none; pointer-events: none; z-index: 1;}' +
        '#content_left>div:hover::before{left: 100%; transition: left 1.2s ease-in-out;}' +
        '#content_left>div:hover{transform: scale(1.015); background-color: #e4f5f4 !important; box-shadow: 0 4px 15px 0 rgba(0,0,0,0.15) !important; transition: transform 0.3s ease, box-shadow 0.3s ease, background-color 0.3s ease !important; z-index: 10;}' +
        // 表格结果悬停效果
        '#content_left>table{background: #f5e4ea !important; position: relative; overflow: hidden;}' +
        '#content_left>table::before{content: ""; position: absolute; top: 0; left: -100%; width: 100%; height: 100%; background: linear-gradient(90deg, transparent, rgba(0, 255, 255, 0.15), rgba(138, 43, 226, 0.12), transparent); transition: none; pointer-events: none; z-index: 1;}' +
        '#content_left>table:hover::before{left: 100%; transition: left 1.2s ease-in-out;}' +
        '#content_left>table:hover{transform: scale(1.015); background-color: #e4f5f4 !important; box-shadow: 0 4px 15px 0 rgba(0,0,0,0.15) !important; transition: transform 0.3s ease, box-shadow 0.3s ease, background-color 0.3s ease !important; z-index: 10;}'
    );

    if(getDOM('#su')) getDOM('#su').onclick = function() {currentUrl = document.location.href; currentPage = getUrlParam("pn");}
    if(getDOM('#kw')) getDOM('#kw').onkeydown = function() {if(event.keyCode==13) {currentUrl = document.location.href; currentPage = getUrlParam("pn");}}
}

// ==================== Bing搜索初始化 ====================
function initBing() {
    // 增强页面立体效果 - 渐变背景
    GM_addStyle(
        'body{background: linear-gradient(180deg, #f0f2f5 0%, #ffffff 100%) !important;}'
    );
    
    // 搜索框样式 - 居中显示
    GM_addStyle(`
        /* 必应搜索框居中 */
        #sb_form { max-width: 800px !important; margin: 0 auto !important; width: 100% !important; display: flex !important; justify-content: center !important; }
        .b_searchboxForm { max-width: 800px !important; margin: 0 auto !important; width: 100% !important; }
        #searchbox { max-width: 800px !important; margin: 0 auto !important; }
    `);
    
    modifyDOM('#sb_form_q', 'border-radius: 24px !important; padding: 10px 20px !important; font-size: 16px !important;');
    
    // 去除右侧边栏
    hideDOM('#b_context');
    
    // 宽屏单列布局 - 解决留白问题
    GM_addStyle(`
        /* Bing宽屏居中布局 - 更宽适配 */
        #b_content { width: min(92vw, 1400px) !important; margin: 0 auto !important; padding: 0 24px !important; float: none !important; }
        #b_results { width: 100% !important; max-width: 100% !important; float: none !important; }
        /* 让搜索结果卡片撑满宽度 */
        .b_algo { width: 100% !important; max-width: 100% !important; }
        /* Bing结果卡片美化 */
        .b_algo { background: #f5e4ea !important; border-radius: 12px !important; padding: 16px !important; margin-bottom: 16px !important; box-shadow: 0 2px 8px rgba(0,0,0,0.08) !important; position: relative; overflow: hidden; }
        /* 隐藏侧边推荐 */
        #b_context, #b_pole, #b_footer { display: none !important; }
        /* 隐藏必应分页栏(使用自动翻页) */
        #b_pag, #b_pag ul, .sb_pag, nav[role="navigation"], .b_pag { display: none !important; visibility: hidden !important; height: 0 !important; overflow: hidden !important; }
        /* 鼠标悬停渐变光层效果 */
        .b_algo::before { content: ""; position: absolute; top: 0; left: -100%; width: 100%; height: 100%; background: linear-gradient(90deg, transparent, rgba(0, 255, 255, 0.15), rgba(138, 43, 226, 0.12), transparent); transition: none; pointer-events: none; z-index: 1; }
        .b_algo:hover::before { left: 100%; transition: left 1.2s ease-in-out; }
        .b_algo:hover { transform: scale(1.015); background-color: #e4f5f4 !important; box-shadow: 0 4px 15px rgba(0,0,0,0.15) !important; transition: transform 0.3s ease, box-shadow 0.3s ease, background-color 0.3s ease !important; z-index: 10; }
        /* 顶部导航栏透明效果 */
        #b_header { background-color: rgba(248,248,248,0.4) !important; backdrop-filter: blur(10px); }
        /* 图片结果样式 */
        .b_imageItem { border-radius: 12px !important; overflow: hidden !important; }
        /* 工具栏样式 */
        #b_tween { background-color: rgba(248,248,248,0.4) !important; }
        /* 隐藏Deep dive推荐搜索和相关搜索 */
        .b_rs, .b_ans.b_slug, li.b_ans, .b_dynSlice, #brsv3, .b_rrsr, #b_results li.b_ans, #b_results [id*="Deep dive"] { display: none !important; }
        /* 搜索建议下拉框 */
        .sa_as { background: rgba(255,255,255,0.98) !important; border-radius: 12px !important; box-shadow: 0 4px 15px rgba(0,0,0,0.15) !important; }
    `);
    
    // Bing翻页变量
    window.bingCurrentUrl = document.location.href;
    window.bingCurrentPage = getBingPageNum();
}

/**
 * 获取Bing当前页码
 */
function getBingPageNum() {
    const firstResult = getDOM('.b_algo');
    if (!firstResult) return 1;
    const urlParams = new URLSearchParams(window.location.search);
    const first = parseInt(urlParams.get('first')) || 1;
    return Math.floor(first / 10) + 1;
}

/**
 * Bing自动翻页(可选功能,需要用户手动触发)
 */
function loadNextPageBing() {
    // 防重入检查
    if (window.bingLoading) {
        console.log('[搜索美化] Bing正在加载中,忽略重复请求');
        return;
    }
    window.bingLoading = true;
    showToast('加载中...');
    
    var xhr = new XMLHttpRequest();
    var urlParams = new URLSearchParams(window.location.search);
    var currentFirst = parseInt(urlParams.get('first')) || 1;
    var nextFirst = currentFirst + 10;
    
    // 保留其他参数,只更新first
    urlParams.set('first', nextFirst);
    var nextPageUrl = window.location.pathname + '?' + urlParams.toString();
    
    console.log('[搜索美化] Bing加载下一页:', nextPageUrl);
    
    xhr.open("GET", nextPageUrl);
    xhr.send();
    
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.status === 200){
            var parser = new DOMParser();
            var doc = parser.parseFromString(xhr.responseText, "text/html");
            var results = doc.querySelectorAll('.b_algo');
            var container = getDOM('#b_results');
            
            console.log('[搜索美化] Bing找到结果:', results.length);
            
            if (container && results.length > 0) {
                for (var i = 0; i < results.length; i++) {
                    container.appendChild(results[i].cloneNode(true));
                }
                showToast('已加载更多结果');
                // 重新绑定Bing卡片点击事件
                bindBingCardClick();
            } else {
                showToast('没有更多结果了');
            }
            window.bingLoading = false;
        } else if (xhr.readyState === 4 && xhr.status !== 200) {
            console.error('[搜索美化] Bing请求失败:', xhr.status);
            showToast('加载失败');
            window.bingLoading = false;
        }
    }
    
    window.bingCurrentUrl = nextPageUrl;
}

/**
 * 绑定Bing卡片点击事件(整个卡片可点击)
 */
function bindBingCardClick() {
    const results = getDOMs('.b_algo');
    results.forEach(function(card) {
        card.style.cursor = 'pointer';
        card.onclick = function(e) {
            const link = card.querySelector('h2 a, a[href]');
            if (link && !e.target.closest('a')) {
                e.preventDefault();
                window.location.href = link.href;
            }
        };
    });
}

// ==================== 全局变量和事件绑定 ====================
var currentUrl = document.location.href;
var currentPage = getUrlParam("pn");

// 防重入标志
window.baiduLoading = false;
window.bingLoading = false;

// 滚动事件防抖定时器
window.scrollDebounceTimer = null;

// 已加载的页码记录
window.loadedPages = new Set();
window.loadedPages.add(parseInt(currentPage) || 0);

console.log('[搜索美化] 脚本初始化完成,引擎:', getSearchEngine());
console.log('[搜索美化] 初始页码:', currentPage);

/**
 * 百度自动翻页(修复版 - 带防重入机制)
 */
function loadNextPage(){
    // 防重入检查
    if (window.baiduLoading) {
        console.log('[搜索美化] 百度正在加载中,忽略重复请求');
        return;
    }
    
    var nextPage;
    if(currentPage == null){
        currentPage = 0;
        nextPage = 10;
    } else {
        nextPage = parseInt(currentPage) + 10;
    }
    
    // 检查是否已加载过这一页
    if (window.loadedPages.has(nextPage)) {
        console.log('[搜索美化] 第', nextPage, '页已加载过,跳过');
        return;
    }
    
    window.loadedPages.add(nextPage);
    window.baiduLoading = true;
    
    showToast('加载第' + (nextPage/10 + 1) + '页...');
    console.log('[搜索美化] 开始加载第', nextPage/10 + 1, '页');
    
    var xhr = new XMLHttpRequest();
    var nextPageUrl;
    
    // 构造下一页URL
    if(currentUrl.includes('pn=')){
        nextPageUrl = currentUrl.replace(/pn=\d*/, 'pn=' + nextPage);
    } else if (currentUrl.includes('?')) {
        nextPageUrl = currentUrl + '&pn=' + nextPage;
    } else {
        nextPageUrl = currentUrl + '?pn=' + nextPage;
    }
    
    console.log('[搜索美化] 下一页URL:', nextPageUrl);
    
    xhr.open("GET", nextPageUrl);
    xhr.send();
    
    xhr.onreadystatechange = function(){
        if(xhr.readyState === 4 && xhr.status === 200){
            var parser = new DOMParser();
            var doc = parser.parseFromString(xhr.responseText, "text/html");
            
            // 尝试多种选择器获取搜索结果
            var results = doc.querySelectorAll('#content_left > div:not([id^="slider"]), #content_left > table');
            console.log('[搜索美化] 解析到搜索结果数量:', results.length);
            
            var container = document.querySelector('#content_left');
            if (container && results.length > 0) {
                for (var i = 0; i < results.length; i++) {
                    // 排除广告和重复内容
                    var r = results[i];
                    if(!r.querySelector('.ec_wise_ad') && !r.classList.contains('result-op') && !r.classList.contains('help-author-wrap')){
                        container.appendChild(r.cloneNode(true));
                    }
                }
                showToast('已加载第' + (nextPage/10 + 1) + '页');
                console.log('[搜索美化] 成功追加结果到第', nextPage/10 + 1, '页');
                
                // 重新应用样式到新加载的内容
                setTimeout(function(){
                    var newCards = document.querySelectorAll('#content_left > div:not([data-styled]):not([id^="slider"]), #content_left > table:not([data-styled])');
                    newCards.forEach(function(card){
                        card.setAttribute('data-styled', 'true');
                        card.style.background = '#f5e4ea';
                        card.style.borderRadius = '12px';
                        card.style.marginBottom = '20px';
                        card.style.padding = '16px';
                        card.style.boxShadow = '0 2px 5px rgba(0,0,0,0.1)';
                        card.style.position = 'relative';
                        card.style.overflow = 'hidden';
                    });
                }, 100);
                
                // 检查是否需要继续加载
                var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
                var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
                console.log('[搜索美化] clientHeight:', clientHeight, 'scrollHeight:', scrollHeight);
            } else {
                showToast('没有更多结果了');
                console.log('[搜索美化] 未找到更多结果');
            }
            
            // 重置状态,允许下一次加载
            window.baiduLoading = false;
        } else if (xhr.readyState === 4 && xhr.status !== 200) {
            console.error('[搜索美化] 请求失败,状态码:', xhr.status);
            showToast('加载失败,请检查网络');
            window.baiduLoading = false;
            // 移除已记录但加载失败的页码,允许重试
            window.loadedPages.delete(nextPage);
        }
    }
    
    currentUrl = nextPageUrl;
    currentPage = nextPage;
}

function scrollToTopF(){
    window.scrollTo({ left: 0, top: 0, behavior: 'smooth' });
}

// ==================== 主程序入口 ====================
( function() {
    'use strict';
    
    const engine = getSearchEngine();
    
    // 初始化
    init();
    
    document.addEventListener('DOMContentLoaded',function(e){
        generateScrollToTopElement();
        
        // 根据不同搜索引擎绑定卡片点击事件
        if (engine === 'baidu') {
            // 让整个卡片可点击(添加空值检查,防止元素不存在时报错)
            const contentLeft = document.querySelector('#content_left');
            if (contentLeft) {
                contentLeft.addEventListener('click', function(e) {
                    const card = e.target.closest('#content_left > div, #content_left > table');
                    if (card) {
                        const link = card.querySelector('a[href]');
                        if (link && !e.target.closest('a')) {
                            e.preventDefault();
                            link.click();
                        }
                    }
                });
            }
        } else if (engine === 'bing') {
            // Bing卡片点击事件
            setTimeout(function() {
                bindBingCardClick();
            }, 1000);
        }
    });
    
    window.onload = function(){
        // 百度页面:强制居中
        if (engine === 'baidu') {
            forceCenterLayout();
        }
        
        // 添加观察者,监控样式变化(添加防抖避免无限循环)
        var observerDebounce = null;
        var observer = new MutationObserver(function(mutations) {
            // 防抖:300ms内只执行一次
            clearTimeout(observerDebounce);
            observerDebounce = setTimeout(function() {
                if (engine === 'baidu') {
                    forceCenterLayout();
                }
            }, 300);
        });
        
        // 根据不同搜索引擎选择观察目标
        if (engine === 'baidu') {
            var target = document.querySelector('#wrapper');
            if (target) {
                observer.observe(target, { attributes: true });
            }
        } else if (engine === 'bing') {
            var bingTarget = document.querySelector('#b_results');
            if (bingTarget) {
                observer.observe(bingTarget, { childList: true, subtree: true });
            }
        }
    }
    
    // 使用 requestAnimationFrame 优化滚动事件
    let ticking = false;
    window.addEventListener('scroll', function() {
        if (!ticking) {
            window.requestAnimationFrame(function() {
                handleScroll();
                ticking = false;
            });
            ticking = true;
        }
    });
    
    function handleScroll() {
        let scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        let clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
        let scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
        
        // 回到顶部按钮显示/隐藏
        if(scrollTop <= 200) {
            replaceDOMClass('.scrollToTop', 'show', 'hide');
        } else {
            replaceDOMClass('.scrollToTop', 'hide', 'show');
        }
        
        // 防抖:使用 setTimeout 确保在滚动停止后才触发加载
        if (window.scrollDebounceTimer) {
            clearTimeout(window.scrollDebounceTimer);
        }
        
        // 滚动到底部检测 - 需要滚动停止后100ms才触发
        window.scrollDebounceTimer = setTimeout(function() {
            // 百度自动翻页
            if (engine === 'baidu') {
                // 只在真正滚动到底部时触发
                var distanceToBottom = scrollHeight - scrollTop - clientHeight;
                console.log('[搜索美化] 百度滚动检测 - 距底部:', distanceToBottom, 'px');
                if (distanceToBottom <= 50) { // 距离底部50px内才触发
                    loadNextPage();
                }
            }
            
            // Bing自动翻页
            if (engine === 'bing') {
                var distanceToBottom = scrollHeight - scrollTop - clientHeight;
                console.log('[搜索美化] Bing滚动检测 - 距底部:', distanceToBottom, 'px');
                if (distanceToBottom <= 50) {
                    loadNextPageBing();
                }
            }
        }, 100);
    }
} )();