1、获取一个DOM元素的属性
-
- <div ref="myDiv" style="margin-top: 100px;">
- 我是一个div容器
- div>
- <button @click="getDistance">获取距离顶部的距离button>
-
-
- <script>
- import { ref } from 'vue'
-
- export default {
- setup() {
- const myDiv = ref(null)
-
- const getDistance = () => {
- if (myDiv.value) {
- const distance = myDiv.value.getBoundingClientRect().top
- console.log('距离顶部的距离:', distance)
- }
- }
-
- return {
- myDiv,
- getDistance
- }
- }
- }
- script>