当前位置:首页 > 编程笔记 > 正文
已解决

【js】vue获取document.getElementById(a)为null

来自网友在路上 150850提问 提问时间:2023-11-06 06:11:04阅读次数: 50

最佳答案 问答题库508位专家为你答疑解惑

需求

在菜单A页面点击某个元素携带id跳转到B详情页面,B页面获取该id元素的offsetTop, 并自动滚动到该元素处

问题

跳转到B详情页面, 在mounted获取到document.getElementById(a)为null, 因为整个详情页面是从后端获取来渲染的数据, 因此此时dom元素还未渲染出来, 所以拿到的是null, 但是尝试过以下两种办法均无效:

  1. this.$nextTick(function() {}) 在这里获取dom, 无效
  2. 在接口请求完成后再获取元素, 无效
  3. 在created请求接口, mounted获取元素, 无效
  mounted() {this.id = this.$route.params.id;let a = "section" + this.id;var top = document.getElementById(a).offsetTop;$(window).scrollTop(top + 300);$("#myNav").affix({offset: {top: 300}});},

解决

还是得用上计时器做点延迟才行…

  mounted() {setTimeout(() => {this.id = this.$route.params.id;let a = "section" + this.id;var top = document.getElementById(a).offsetTop;$(window).scrollTop(top + 300);$("#myNav").affix({offset: {top: 300}});var wow = new WOW();wow.init();}, 300);},
查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"【js】vue获取document.getElementById(a)为null":http://eshow365.cn/6-33393-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!