解决TS报错Property 'style' does not exist on type 'Element'

在使用queryselector获取一个dom元素,编译时却报错说property 'style' does not exist on type 'element'。

原因:这是typescript的类型检查导致的,需要在querySelector方法前面加个类型断言。

let frameContainObj = document.getElementById("model_view_container")
let iframeObj= <HTMLElement>frameContainObj.querySelector("#modelView");
iframeObj.style.height = document.documentElement.clientHeight* 0.65 + "px";

扩展:当使用queryselectorall时,可以采用如下方案:

let block = document.querySelectorAll(".block") as NodeListOf<HTMLElement>;

参考资料:https://github.com/Microsoft/TypeScript/issues/3263

https://segmentfault.com/q/1010000011796234/a-1020000011796986

猜你喜欢

转载自www.cnblogs.com/PearlRan/p/10155754.html
今日推荐