7 javascript jquery typescript
我使用以下代码:
$('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top });
Run Code Online (Sandbox Code Playgroud)
打字稿给我一条错误信息说:
The property 'top' does not exist on value of type 'Object'
Run Code Online (Sandbox Code Playgroud)
我猜jQuery定义文件中缺少某些东西.有没有其他人看到这个问题,或者这是通常不与jQuery一起使用的东西?这是我以前没见过的东西.
欲获得更多信息.以下是使用它的代码:
$.fn.buildTableOfContent = function () {
"use strict";
var h2 = this.find('h2');
if (h2.length > 0) {
var h1 = this.find('h1:first');
if (h1.length === 0) {
h1 = this.prepend('<h1>Help</h1>').children(':first');
}
var menu = h1.wrap('<div class="h1 with-menu"></div>')
.after('<div class="menu"><img src="/Content/images/menu-open-arrow.png" width="16" height="16"><ul></ul></div>')
.next().children('ul');
h2.each(function (i) {
this.id = 'step' + i;
menu.append('<li class="icon_down"><a href="#step' + i + '">' + $(this).html() + '</a></li>');
});
menu.find('a').click(function (event) {
event.preventDefault();
$('html, body').animate({ scrollTop: $($(this).attr('href')).offset().top });
});
}
return this;
};
Run Code Online (Sandbox Code Playgroud)
来自 jquery.d.ts 文件(我的版本中的第 374 行):
interface JQuery {
...
offset(): Object;
offset(coordinates: any): JQuery;
offset(func: (index: any, coords: any) => any): JQuery;
...
}
Run Code Online (Sandbox Code Playgroud)
通过调用不带参数的函数,类型定义期望函数返回一个Object类型。我查看了 jQuery 的文档,你是对的,返回的对象应该具有top和left属性。
不幸的是,由于不存在基于返回类型的重载,因此您无法将另一个成员添加到接口上JQuery。因为在这种特殊情况下,类型定义根本没有应有的那么具体,所以我建议简单地修改 jquery.d.ts 文件并更改返回类型,使其看起来如下(可能是字符串而不是数字?):
offset(): { top : number; left : number; };
Run Code Online (Sandbox Code Playgroud)
如果您不想修改此文件,您还可以选择any在访问该文件上的任何属性之前将结果转换为:
$('html, body').animate({ scrollTop: (<any> $($(this).attr('href')).offset()).top });
Run Code Online (Sandbox Code Playgroud)
缺点是每次调用不带参数的函数时都需要进行强制转换。
| 归档时间: |
|
| 查看次数: |
1474 次 |
| 最近记录: |