iPhone兼容性修復(fù):吸頂效果的Tabs標(biāo)簽頁組件的完美自定義
前言
當(dāng)我們開發(fā)Web應(yīng)用或移動應(yīng)用時,經(jīng)常需要使用標(biāo)簽頁(Tabs)組件來切換不同的內(nèi)容或功能模塊。標(biāo)簽頁在用戶體驗(yàn)中扮演著關(guān)鍵角色,但有時候,我們需要更多的控制和自定義來滿足特定項(xiàng)目的需求。在近期的開發(fā)中,我實(shí)現(xiàn)了一個強(qiáng)大而實(shí)用的功能——吸頂效果的Tabs標(biāo)簽頁組件。
在這篇文章中,我將與大家分享我的實(shí)際開發(fā)經(jīng)驗(yàn),重點(diǎn)關(guān)注如何自定義實(shí)現(xiàn)吸頂效果的Tabs標(biāo)簽頁組件。通過本文,您將了解到如何充分發(fā)揮前端開發(fā)的靈活性和創(chuàng)造力,以滿足項(xiàng)目的特定要求。無論您是一個有經(jīng)驗(yàn)的前端工程師還是一個剛剛?cè)腴T的新手,我相信這篇文章都會為您提供有價值的見解和靈感。
讓我們開始探索如何打造完美的自定義吸頂效果的Tabs標(biāo)簽頁組件,為您的項(xiàng)目增添更多的魅力和功能!
1. 交互主要功能和交互簡介
在我們深入探討如何自定義實(shí)現(xiàn)吸頂效果的Tabs標(biāo)簽頁組件之前,讓我們先來了解一下這個組件的主要功能和交互,以便更好地理解我們將要進(jìn)行的優(yōu)化和改進(jìn)。這個組件通常包括以下核心功能和交互特性(效果如下):
頁面頂部呈現(xiàn)車系名稱和車系圖片,您可以選擇不同的車型以查看相關(guān)權(quán)益。在頭部以下,我們有兩級導(dǎo)航。當(dāng)您滾動頁面到頂部時,導(dǎo)航會自動吸附在頂部。當(dāng)切換二級選項(xiàng)卡時,選中的選項(xiàng)卡會高亮顯示,并且頁面內(nèi)容自動滾動到頂部以顯示相關(guān)內(nèi)容。如果手動滾動頁面,例如將付費(fèi)服務(wù)內(nèi)容滾動到頂部,那么付費(fèi)服務(wù)選項(xiàng)卡將高亮顯示。
您還可以打開汽車之家 app,掃描以下二維碼來查看演示效果。
圖片
整體代碼移步:https://code.juejin.cn/pen/7264502984589967396
2. 吸頂效果 - 技術(shù)方案及實(shí)現(xiàn)
圖片
? 最終選擇方案
該頁面需要兼容的機(jī)型有,以上機(jī)型都能兼容position: sticky,無兼容問題。所以采用了實(shí)現(xiàn)起來較為簡單的設(shè)置position: sticky的方式。
position: sticky 代碼實(shí)現(xiàn):
.tab-container {
position: sticky;
top: 0px;
z-index: 9;
}
? 監(jiān)聽滾動事件代碼實(shí)現(xiàn):
import React, { useState, useEffect } from 'react@18';
import { createRoot } from 'react-dom@18/client';
const Test = function () {
useEffect(() => {
// 回到頂部
function handleScrollChange() {
const selHtml = document.getElementById('sel');
const scrH: number =
document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop || 0;
if (selHtml) {
if (scrH >= 105) {
selHtml.style.position = 'fixed';
selHtml.style.top = `0px`;
selHtml.style.zIndex = '20';
} else {
selHtml.style.position = 'absolute';
selHtml.style.top = `0px`;
}
}
}
window.addEventListener('scroll', handleScrollChange);
}, []);
return <div>
<div className="header"></div>
<div className='tab-container-box'>
<div id="placeholder" style={{ height: '100%', backgroundColor: '#fff' }} />
<div className={`tab-container`} id="sel">
.....吸頂塊
</div>
</div>
<div className="footer"></div>
</div>;
};
const app = document.getElementById('app');
const root = createRoot(app!)
root.render(<Test />);
3. tab 點(diǎn)擊效果 - 技術(shù)方案及實(shí)現(xiàn)
首先想到“Ant Design Mobile Tabs標(biāo)簽頁組件”(https://mobile.ant.design/zh/components/tabs/) 能夠?qū)崿F(xiàn)新能源車主權(quán)益中的切換tab滾動定位、手動滑動頁面相應(yīng)tab高亮的功能,但是通過兼容性測試,發(fā)現(xiàn)該組件在一些iPhone機(jī)型上切換,tab,tab抖動。以下是iphone 14機(jī)型交互效果:
圖片
那就自定義一個組件吧。
圖片
?Intersection Observer API 代碼實(shí)現(xiàn)
import React, { useState, useEffect,useRef } from 'react@18';
import { createRoot } from 'react-dom@18/client';
const Test = function () {
const nextKey = useRef(null);
const [activeIdx,setActiveIdx]=useState<number>(0);
const [inView, setInView] = useState<string[]>([]);
const tabs=[
{
"key":"mianfei",
"value":"免費(fèi)權(quán)益",
"type":1
},
{
"key":"fufei",
"value":"付費(fèi)服務(wù)",
"type":2
}
];
const onTabClick = (idx: number) => {
nextKey.current = idx;
const element = document.getElementById(tabs[idx]?.key);
const h=document.getElementById('sel').clientHeight;
const offset = element.getBoundingClientRect().top-h;
window.scrollTo({
top: offset,
behavior: 'smooth'
});
};
const scrollhandle = () => {
const targets = document.querySelectorAll('.tab-content');
const headerH = Number(document.getElementById('sel')?.clientHeight) ;
const options = {
rootMargin: `-${headerH}px 0px`,
};
const callback = (entries) => {
const arr = inView;
entries.forEach((entry) => {
const dataUi: string = entry.target.getAttribute('data-service');
console.log(entry.target)
if (entry.isIntersecting) {
if (!arr.includes(dataUi)) {
arr.push(dataUi);
}
} else {
if (arr.indexOf(dataUi) > -1) {
arr.splice(arr.indexOf(dataUi), 1);
}
}
});
arr.sort((a, b) => Number(a) - Number(b));
setInView(arr);
if (nextKey.current == -1 || nextKey.current == Number(arr[0])) {
nextKey.current = -1;
setActiveIdx(Number(arr[0]));
}
};
const observer = new IntersectionObserver(callback, options);
targets.forEach((target) => {
observer.observe(target);
});
return observer;
};
useEffect(()=>{
let observer = null;
if (tabs.length) {
observer = scrollhandle();
setActiveIdx(0);
}
return () => {
observer?.disconnect();
};
},[])
return (<div>
<div id='sel'>
<div className="tab-container">
{
tabs?.map((tab, idx) => (
<button
className={`tab ${idx == activeIdx ? 'active' : ''}`}
key={`${tab.key}_tab`}
onClick={() => {
onTabClick(idx);
}}
>{tab.value}</button>))
}
</div>
<div className='h-[50px]'></div>
</div>
<div className="content-box">
{tabs?.map((tab,idx) => (
<div key={tab.key} data-service={idx} className="tab-content" id={tab.key} style={{ minHeight:idx==tabs.length-1?'100dvh':'auto' }}>
<p>{tab.value}</p>
</div>
))}
</div>
</div>);
}
const app = document.getElementById('app');
const root = createRoot(app!)
root.render(<Test />);
? 監(jiān)聽滾動事件代碼實(shí)現(xiàn)
import React, { useState, useEffect } from 'react@18';
import { createRoot } from 'react-dom@18/client';
const Test = function () {
const [activeIdx,setActiveIdx]=useState<Number>(0);
const tabs=[
{
"key":"mianfei",
"value":"免費(fèi)權(quán)益",
"type":1
},
{
"key":"fufei",
"value":"付費(fèi)服務(wù)",
"type":2
}
];
const onTabClick = (idx: number) => {
setActiveIdx(idx);
const element = document.getElementById(tabs[idx]?.key);
const h=document.getElementById('sel').clientHeight;
const offset = element.getBoundingClientRect().top-h;
window.scrollTo({
top: offset,
behavior: 'smooth'
});
};
const onscroll = () => {
const h=document.getElementById('sel').clientHeight;
tabs.forEach((tab, idx) => {
const el = document.getElementById(tab?.key);
const rect = el?.getBoundingClientRect() || { top: 0, bottom: 0 };
if (rect?.top <= h && rect?.bottom > h || (idx === 0 && rect?.top >= h)) {
setActiveIdx(idx);
}
});
};
useEffect(()=>{
window.addEventListener('scroll', onscroll, true);
return ()=>{
window.removeEventListener('scroll', onscroll);
}
},[
])
return (<div>
<div className="tab-container-box" id='sel'>
<div className="tab-container">
{
tabs?.map((tab, idx) => (
<button
className={`tab ${idx == activeIdx ? 'active' : ''}`}
key={`${tab.key}_tab`}
onClick={() => {
onTabClick(idx);
}}
>{tab.value}</button>))
}
</div>
</div>
<div className='mt-[20px]'>
{tabs?.map((tab, idx) => (
<div key={tab.key} className="tab-content" id={tab.key} style={{ minHeight:'100dvh' }}>
<p>{tab.value}</p>
</div>
))}
</div>
</div>);
}
const app = document.getElementById('app');
const root = createRoot(app!)
root.render(<Test />);
? 最終選擇實(shí)現(xiàn)方案
給 tab 添加點(diǎn)擊事件執(zhí)行 onTabClick 方法,在 onTabClick 方法里計(jì)算需要滾動的高度,利用 scrollTo 方法設(shè)置滾動距離。通過 IntersectionObserver 方法監(jiān)聽權(quán)益內(nèi)容模塊的滾動情況,當(dāng)權(quán)益內(nèi)容滾動到權(quán)益內(nèi)容可視區(qū)頭部時,當(dāng)前 tab 添加高亮效果。
需要注意的點(diǎn):
定義 nextKey 變量,用來判斷 tab 點(diǎn)擊后頁面本次滾動是否結(jié)束,結(jié)束后在給當(dāng)前 tab 添加高亮效果,防止高亮效果在 tab 上來回切換
給最后一個權(quán)益內(nèi)容模塊設(shè)置最小高度,保證內(nèi)容能滾動到權(quán)益內(nèi)容可視區(qū)域頭部
4. 服務(wù)介紹的收起與展開
封裝TextCollapse 組件,組件中添加兩個 div,其內(nèi)容都是要展示的權(quán)益內(nèi)容,一個 div 正常展示,設(shè)置最大高度超出隱藏。兩外一個不設(shè)置高度,設(shè)置絕對定位及透明度為 0,通過第二個div判斷文字實(shí)際高度。文字實(shí)際高度大于最大高度,則展示展開按鈕;反之,則隱藏。
?需要注意的點(diǎn)
引用組件時 key 值不能只用權(quán)益內(nèi)容 id。因?yàn)橄嗤臋?quán)益內(nèi)容可能出現(xiàn)在不同權(quán)益類型下,這時如果使用 id 做為 key 值,切換權(quán)益類型 tab 時,TextCollapse 內(nèi)容不會重新渲染,被展開的內(nèi)容不能恢復(fù)收起狀態(tài)。這里我使用了 item.id+activeKey 做為 key 值。
<TextCollapse key={item.id+activeKey} text={item.content} maxLines={8} />
?代碼實(shí)現(xiàn)
import React, { useState, useEffect, useRef } from 'react@18';
import { createRoot } from 'react-dom@18/client';
type TextCollapseT = {
text: string;
maxLines: number;
};
const TextCollapse = ({ text, maxLines }: TextCollapseT) => {
const [expanded, setExpanded] = useState(false);
const [shouldCollapse, setShouldCollapse] = useState(false);
const textRef = useRef(null);
useEffect(() => {
if (textRef?.current?.clientHeight) {
setShouldCollapse(textRef.current.clientHeight > maxLines * 20);
}
}, []);
const toggleExpand = () => {
setExpanded(!expanded);
};
const textStyles = {
display: '-webkit-box',
WebkitBoxOrient: 'vertical',
overflow: 'hidden',
overflowWrap: 'break-word',
wordBreak: 'break-word',
WebkitLineClamp: expanded ? 'unset' : maxLines,
whiteSpace: 'pre-wrap',
};
return (
<div className="text-collapse">
<div style={textStyles} className="article">
{text}
</div>
<div
style={{ ...textStyles, WebkitLineClamp: 'unset' }}
className="article hide-art"
ref={textRef}
>
{text}
</div>
{shouldCollapse && !expanded ? (
<button onClick={toggleExpand} className="btn">
展開查看更多
</button>
) : null}
</div>
);
};
const app = document.getElementById('app');
const root = createRoot(app!);
const cnotallow="9月4日,茅臺與瑞幸推出的聯(lián)名咖啡“醬香拿鐵”正式上架銷售了。9月4日,茅臺與瑞幸推出的聯(lián)名咖啡“醬香拿鐵”正式上架銷售了。9月4日,茅臺與瑞幸推出的聯(lián)名咖啡“醬香拿鐵”正式上架銷售了。9月4日,茅臺與瑞幸推出的聯(lián)名咖啡“醬香拿鐵”正式上架銷售了。9月4日,茅臺與瑞幸推出的聯(lián)名咖啡“醬香拿鐵”正式上架銷售了。9月4日,茅臺與瑞幸推出的聯(lián)名咖啡“醬香拿鐵”正式上架銷售了。"
root.render(<TextCollapse key={123} text={content} maxLines={6} />);
?兼容機(jī)型及系統(tǒng)
圖片
作者簡介
王晶
■ 客戶端研發(fā)部-前端團(tuán)隊(duì)-C端組
■ 2015年加入汽車之家,目前主要負(fù)責(zé)汽車之家搜索以及新能源相關(guān)h5頁面的前端開發(fā)工作。