调整网页大小或更换大屏时如何保持.trans1元素位置不偏移
问题根源
你当前使用固定百分比translateX(180%)和left:11%定位滑块,百分比数值是相对于父容器宽度计算的,浏览器窗口大小变化时父容器宽度同步改变,相同百分比对应的实际像素位移也会变化,自然会偏离对应按钮的位置。
修复方案
1. 调整CSS定位逻辑,将滑块的定位基准绑定到按钮容器
/* 给按钮容器加相对定位,作为滑块的定位基准 */ .selectBtns { position: relative; display: flex; gap: 0; } /* 修改滑块定位规则,取消百分比偏移 */ .trans1 { z-index: 980; margin-top: 3px; position: absolute; top: 100%; /* 固定放在按钮正下方 */ left: 0; transition: transform 0.8s; } /* 清理原有冗余定位规则 */ .trans-container { position: relative; width: 100%; height: auto; } #make-trans { width: 100%; }
2. 修改JS逻辑,动态计算位移距离,窗口变化时自动校准
const tranImg= document.getElementById('trans'); const firstBtn = document.getElementById('btn2'); window.onload= trans; // 窗口大小变化时重新校准滑块位置 window.onresize = () => { tranImg.dataset.active === 'landing' ? trans() : trans2() } function trans(){ tranImg.style.transform = `translateX(0)`; tranImg.dataset.active = 'landing' const xhr = new XMLHttpRequest(); xhr.open("GET", "splash.html"); xhr.onreadystatechange = () => { if(xhr.readyState === 4){ document.querySelector(".app").innerHTML = xhr.response; } }; xhr.send(); }; function trans2(){ // 动态取第一个按钮的宽度作为位移值,自动适配不同尺寸 const offset = firstBtn.offsetWidth; tranImg.style.transform = `translateX(${offset}px)`; tranImg.dataset.active = 'website' const xhr = new XMLHttpRequest(); xhr.open("GET", "website.html"); xhr.onreadystatechange = () => { if(xhr.readyState === 4){ document.querySelector(".app").innerHTML = xhr.response; } }; xhr.send(); };
3. 调整HTML结构,保证定位基准正确
<div class="selectBtns"> <button class="btns" id="btn2" onclick="trans()">Landing page</button> <button class="btns" onclick="trans2()">Website</button> <!-- 滑块移入按钮容器内,绑定定位基准 --> <img id="trans" class="trans1" src="./images/svg-path (1).svg" alt="transition tab" width="400px"> </div> <div class="trans-container"> <div class="xml-change"> <div class="app"></div> </div> </div>
内容的提问来源于stack exchange,提问作者LM17
相关产品推荐
相关产品推荐

