gpt4 book ai didi

javascript - CSS 未捕获类型错误 : Cannot read property 'setAttribute' of null

转载 作者:太空宇宙 更新时间:2023-11-03 19:55:52 25 4
gpt4 key购买 nike

我正在尝试将 margin-top:10px 分配给 id download-csv

这是 html 和 javascrpit:

<span style="display: inline;"  id="download-csv"><input type="submit"   id="csv_download"  value="Download"></span>;



JavaScript :
var download_csv=document.getElementById("download-csv");
if(count_layer==1)
download_csv.setAttribute("style","margin-top:10px");
}else{
download_csv.setAttribute("style","margin-top:20px");

}

它抛出错误 TypeError:无法读取 null 的属性“setAttribute”

最佳答案

您需要确保在 JS 代码访问这些元素之前加载标记。

另外,你不能给 inline 元素 margin,设置 display style 属性 as 内联显示

var download_csv = document.getElementById("download-csv");
var count_layer = 1;
if (count_layer == 1) {
download_csv.style.marginTop = "10px";
} else {
download_csv.style.marginTop = "50px";
}
<span style="display: inline-block;" id="download-csv">
<input type="submit" id="csv_download" value="Download">
</span>

关于javascript - CSS 未捕获类型错误 : Cannot read property 'setAttribute' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46826451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com