vue3?內(nèi)容過多出現(xiàn)滾動條時滾動條自動定位到末端的操作代碼
vue3 內(nèi)容過多出現(xiàn)滾動條時滾動條自動定位到末端的操作代碼
當內(nèi)容過多時,其實已經(jīng)有了滾動條,但視覺上并看不出,要求自動定位到滾動條末端

需要在滾動元素上設(shè)置滾動條的位置,使用ref
<div class="top" ref="tagRef">
<el-tag
type="ghost"
size="large"
v-for="tag in selectTag"
:key="tag.id"
:closable="true"
style="padding-left: 8px; padding-right: 8px"
@close="() => handleClose(tag)"
>
{{
tag.show ||
(Array.isArray(tag.prompt)
? tag.prompt.join(',')
: tag.prompt)
}}
</el-tag>
</div>
const tagRef = ref();
watch(selectTag.value, async() => {
await nextTick();
const topElement = tagRef.value;
if(topElement) {
topElement.scrollTop = topElement.scrollHeight;
}
});擴展:前端vue3-手動設(shè)置滾動條位置/自動定位

從B頁面進行xx操作后需要跳轉(zhuǎn)到A頁面,并定位到AA職位,上圖為A頁面。
A頁面的左側(cè)是div,內(nèi)層包裹List組件

給div定義ref=leftRef,在代碼中寫如下:
function scrollTop() {
if (leftRef.value) {
console.log('99', leftRef.value);
nextTick(() => {
leftRef.value.scrollTop = 1000;
// scrollBy(0, document.body.scrollWidth);
});
}
}
onMounted(async () => {
if (router.currentRoute.value.query.id) {
positionChooseCode.value = router.currentRoute.value.query.id;
positionStatusValue.value = router.currentRoute.value.query.id;
}
const positionId = router.currentRoute.value.query.positionId;
if (!!positionId) {
cStore.setPositionId(positionId);
}
console.log('mounted--positionId', positionId);
await getPositionDictionary(positionChooseCode.value, '');
await getDictionaries();
scrollTop();
});第一,需要等待數(shù)據(jù)渲染完成后,再調(diào)用scrollTop,設(shè)置scrollTop=1000,這樣頁面初始化滾動條位置會改變。
第二,找到當前職位的高度,也要等職位列表數(shù)據(jù)渲染完成后,獲取
console.log('positionList.value', positionList.value);
rowItemId.value = item.id;
//找到前面有多少個元素
let index = positionList.value.findIndex((it) => it.id === rowItemId.value);
console.log('找到前面有多少個元素', index + 1);
num.value = index - 2;
獲取當前職位,當前職位會有class==red的,通過class獲取ele;
const sortableEles = document.querySelectorAll('.red');
console.log(sortableEles);
let itemHeight = 0;
if (sortableEles.length > 0) {
const firstListItem = sortableEles[0];
itemHeight = firstListItem.offsetHeight; // 獲取元素的高度,包括內(nèi)邊距和邊框
console.log('第一個列表項的高度:', itemHeight);
console.log(' num.value', num.value);
}
完整的scrollTop方法如下

總結(jié):
滾動條要滾動起來
選中含有滾動條的元素,定義一個const leftRef = ref(null),在數(shù)據(jù)加載完成后設(shè)置leftRef.value.scrollTop
滾動條的位置
等待數(shù)據(jù)加載完后獲取當前選中的元素,通過.offsetHeight獲取元素的高度
到此這篇關(guān)于vue3 內(nèi)容過多出現(xiàn)滾動條時,滾動條自動定位到末端的文章就介紹到這了,更多相關(guān)vue3 滾動條自動定位到末端內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
element?el-upload文件上傳覆蓋第一個文件的實現(xiàn)
這篇文章主要介紹了element?el-upload文件上傳覆蓋第一個文件的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-03-03
前端開發(fā)指南之vue-grid-layout的使用實例
vue-grid-layout是一個vue柵格拖動布局的組件,下面這篇文章主要給大家介紹了關(guān)于前端開發(fā)指南之vue-grid-layout使用的相關(guān)資料,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2022-09-09

