js/vue/tsx 中获取dom元素的方法集合

前言:

        整理下常用的获取dom元素的方法。

js:

1、原始的class/id
// 拿到唯一的一个dom元素
document.getElementById('abc')

// 比id多了一个s,并且拿到dom是一个数组
document.getElementsBClassName('abc') 

// 拿到指定的标签的元素,是一个数组
document.getElementsByTagName("div")

// 拿到元素身上的name值为abc的,数组
document.getElementsByName('abc') 
2、进阶版

// 1、获取单个元素
document.querySelector('.abc') //页面上的第一个
document.querySelector('#abc')

// 2、获取所有的元素

document.querySelectorAll('abc')

vue

1、class名、id名获取,跟上面的一样
2、ref、refs获取

<div ref='abc'></div>

this.$refs.abc //拿到dom元素

vue3+tsx

import {  ref } from 'vue'

const searchByte = ref('')

// input的双向绑定

<el-input v-model={searchByte.value}></el-input>

import {  ref } from 'vue'

const scrollRef = ref();

<el-scrollbar ref={scrollRef}></el-scrollbar>

*** 因为 虽然 同是使用element的el-scrollbar  的标签,但是获取dom元素的方法是不同的,如果下面无法使用,需要你在界面上重新找下对应的dom元素。

// 获取滚动区域的属性

const domHeitht = scrollRef.value.wrap$.clientHeight;

const allHeitht = scrollRef.value.wrap$.scrollHeight;



// 修改他的滚动条位置

scrollRef.value.wrap$.scrollTop = 43;



// 如果上面的dom找不到,赋值不成功,就用下面的试试

scrollRef.value.$refs.wrap$.scrollTop = 36

猜你喜欢

转载自blog.csdn.net/weixin_44727080/article/details/133297843