TS中报错说style在element类型中不存在怎么办

我用queryselectorall去获取一个dom元素集合,然而在编译时却报错说property 'style' does not exist on type 'element'。在控制台里看block集合里各个元素是有style属性的,但是用for循环去遍历就没了。求各位大神指教一下,是不是要转类型,或者是要用foreach去遍历?
用的是typescript。
代码:

        var winWidth = document.body.clientWidth;
        var height = winWidth*1.23;
        let block = document.querySelectorAll(".block");
        for(var i=0;i<block.length;i++){
            block.item(i).style.height = height + "px";
        }
        
        
阅读 19.1k
3 个回答

这是typescript的类型检查导致的,需要在你的querySelectorAll方法前面加个类型断言就好了,如下

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

block.item(i).style.height = height + "px";

block[i].style.height = height + "px";

没有写过TS,难道TS的数组里有 .item 这个方法

property 'style' does not exist on type 'element'。
那就是block[i]有问题了 是不是执行操作的时候dom还没有渲染完全

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题