javascript - 如何在函数参数中定义/使用“el”(vue js)
问题描述
我是 VueJS 初学者,所以请多多包涵。
使用“?”时,我需要编写代码以滚动到 id 元素 在网址中。效果和这个一样
但我已经用修复格式关注了这个问题,因为这是我的任务。他们在没有document.getElementById(Query.query).scrollIntoView({behavior: "smooth" });
. 我已经通过添加上面的代码完成了结果。但我不知道如何分成 2 个功能。而且我也不知道如何使用“el”参数调用scrollToHere()。
scrollToHere() 没有在其他地方调用,所以我必须在 anchor() 中包含这个函数,但我不知道怎么做。这个“el”是干什么用的?如何分离代码?任何指导将不胜感激。
<div id="scroll_here"></div>
methods: {
anchor() {
console.log(Query) //query: "scroll_here"
document.getElementById(Query.query).scrollIntoView({behavior: "smooth" });
},
scrollToHere (el) {
// CODE HERE
},
}
解决方案
原始答案el
中的项目是指您打算滚动到的项目。HTMLElement
这是一个两两的过程。首先找到元素,然后向它滚动。
// Assuming this is the html - <div id="scroll_here"></div>
// 1. Find the element using one of the two ways
const el = document.getElementById('scroll_here');
// or alternately,
const el = document.querySelector('#scroll_here');
// 2. Scroll that element into view.
el.scrollIntoView();
您可以使用getElementById
或querySelector
来获取 DOM 树中 HTML 元素的引用。
在您的情况下,您可以在方法中获取元素引用anchor()
并将其传递给scrollToHere()
函数,例如:
methods: {
anchor() {
// { query: "scroll_here" }
console.log(Query);
this.scrollToHere(document.getElementById(Query.query));
},
scrollToHere(el) {
el.scrollIntoView({behavior: "smooth" });
}
}
推荐阅读
- r - How to join two data frames by group?
- arduino - Arduino Uno 可以运行两个以上的软件 uart 通信吗?
- c - 如何在链表中查找重复项?
- jira - Jira - 预计工单完成日期报告
- algorithm - 将 n 人分成 m 组 k 次,重叠最小
- cygwin - Cygwin xclip 在没有 cygXmu-6.dll 的情况下失败
- r - R中的SVM预测
- javascript - 在过滤器javascript中使用额外的变量进行排序
- angular - Angular 2+ append class in directive
- javascript - How to handle input from child to parent in React