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

实现滚动后显示侧边横幅及解决移动端滚动定位异常问题

问题解决:滚动触发侧边横幅显示 + 移动端滚动定位修复

问题1:滚动后侧边横幅不显示的修复

原代码核心问题是滚动事件未正确获取横幅元素,且初始状态未隐藏横幅。修改点:

  • 全局定义横幅变量,确保滚动事件能访问到元素
  • CSS默认将.bannerSide的display设为none,默认隐藏
  • 滚动事件中增加元素存在性判断,避免报错

问题2:移动端滚动到目标区域提前停止的修复

原findPos方法用offsetTop累加的方式在移动端会忽略视口偏移,改用getBoundingClientRect()获取精准位置,同时考虑固定导航栏的高度偏移(如果网站有固定头部)。


修改后的完整代码

<style>
html {
    scroll-behavior: smooth;
    transition-duration: 1000ms; /* 修正原拼写错误transtion → transition */
}

.bannerSide {
    position: fixed;
    height: 40px;
    width: 180px;
    display: none; /* 默认隐藏,滚动后显示 */
    flex-direction: row;
    z-index: 9999;
    background-color: black;
    border-radius: 20px;
    bottom: 50vh;
    right: -1.5vw;
    color: #00F498;
    font-family: "Rubik";
    font-weight: bold;
    text-transform: uppercase;
    justify-content: space-evenly;
    align-items: center;
    letter-spacing: 2px;
    transform: rotate(270deg);
    cursor: pointer;
}
</style>

<script>
let bannerSide; // 全局变量存储横幅元素

setTimeout(() => {
    const newLink = document.createElement('a');
    const text = document.createElement('p');
    const arrow = document.createElement('span');
    
    arrow.innerHTML = "←";
    text.innerText = "Formulário";
    
    newLink.appendChild(arrow);
    newLink.appendChild(text);
    
    newLink.onclick = function () {
        const targetEl = document.getElementById("download");
        if (!targetEl) return;
        
        // 获取目标元素相对于视口的位置,计算滚动目标值
        const rect = targetEl.getBoundingClientRect();
        // 减去顶部固定导航栏高度(根据网站实际调整,示例为80px)
        const scrollTop = window.pageYOffset + rect.top - 80;
        
        window.scrollTo({
            top: scrollTop,
            behavior: 'smooth'
        });
    };
    
    newLink.classList.add('bannerSide');
    document.body.appendChild(newLink);
    
    bannerSide = newLink; // 赋值给全局变量
}, 500);

window.addEventListener('scroll', () => {
    if (!bannerSide) return; // 确保元素已创建
    bannerSide.style.display = window.scrollY > 1000 ? 'flex' : 'none';
});
</script>

关键修改说明

  1. 滚动显示修复:

    • 全局声明bannerSide变量,在元素创建后赋值,解决滚动事件中找不到元素的问题
    • CSS默认隐藏横幅,保证初始状态符合需求
    • 滚动事件增加元素存在性判断,避免控制台报错
  2. 移动端滚动定位修复:

    • 替换findPos方法,使用getBoundingClientRect()结合window.pageYOffset计算精准滚动目标值
    • 增加导航栏高度偏移量,解决移动端滚动提前停止的问题(可根据网站实际固定头部高度调整数值)
    • 使用window.scrollTo的对象参数形式,保持平滑滚动行为的一致性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:20:28