【问题标题】:"Uncaught TypeError: Cannot read property 'style' of null at.. "“未捕获的类型错误:无法读取属性‘样式’的 null at..”
【发布时间】:2018-02-12 17:50:20
【问题描述】:

我在不同的文档中练习了如下所示的样式,它适用于段落和按钮,但对于 div,它拒绝这样做。

第一个document.getElementById('red').style.width="100px"; 语句返回错误

“未捕获的 TypeError:无法读取属性‘style’的 null at..”

当我在另一个文档中尝试它时,它没有将样式放在 function myFunction() {} 状态中就可以工作

有什么想法吗?

<div class="red" > some content</div>
<div class="blue" > some content</div>
<div class="green" > some content</div>

<script type="text/javascript">

document.getElementById('red').style.width="100px";
document.getElementById('blue').style.width="100px";
document.getElementById('green').style.width="100px";
document.getElementById('red').style.height="100px";
document.getElementById('blue').style.height="100px";
document.getElementById('green').style.height="100px";
document.getElementById('red').style.backgroundColor="red";
document.getElementById('blue').style.backgroundColor="blue";
document.getElementById('green').style.backgroundColor="green";
document.getElementById('red').style.borderRadius="50px";
document.getElementById('blue').style.borderRadius="50px";
document.getElementById('green').style.borderRadius="50px";

document.getElementById('red').onclick.display="none";
document.getElementById('blue').onclick.display="none";
document.getElementById('green').onclick.display="none";

</script>

【问题讨论】:

  • 你尝试getElementById,但你的元素只有类而不是id

标签: javascript css


【解决方案1】:

Cannot read property 'style' of null 这给了你很好的提示 - of null。这确实意味着,它没有找到您正在寻找的元素。

这仅仅是因为在 html 中您使用的是类 &lt;div class="red"&gt;

和 javascript 中的 ID document.getElementById('red')

坚持上课:

document.getElementsByClassName('red')[0]

或转换为id

<div id="red">

【讨论】:

    【解决方案2】:

    我认为您需要将 id 添加到您的 div

    <div class="red" id="red" > some content</div>
    
    document.getElementById('red').style.width="100px";
    

    【讨论】:

      【解决方案3】:

      将“class='xxx'”更改(或添加)为“id='xxx'”,即可通过对应的ID获取元素。否则你可以尝试使用https://www.w3schools.com/jsreF/met_document_getelementsbyclassname.asp

      【讨论】:

        【解决方案4】:

        选择登录页面元素。

        let landingPage = document.querySelector("landing-page");
        

        获取数组图像。

        let imgsArray = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg"]
        

        更改背景图片网址。

        landingPage.style.backgroundImage = 'imgs./imgaes/"2.jpg"'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-10-03
          • 1970-01-01
          • 1970-01-01
          • 2012-08-01
          • 2021-11-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多