解決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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM