Javascript queryselector.style.modify "uncaught TypeError"

标签 javascript css selectors-api

<分区>

    <script type="text/javascript">
    var ypos,sH,sH6,sIMG,sH4,sP;
        function trigger(){
        ypos=window.pageYOffset;
        /*..............................................Second page...*/
        sH=document.querySelector("#second h2");
        sH6=document.querySelector("#second h6");
        sIMG=document.querySelectorAll("#second img");
        sH4=document.querySelectorAll("#second h4");
        sP=document.querySelectorAll("#second p");
        /*.....................................Second page trigger...*/

        console.log(ypos);
            sH.style.opacity=0;
            if(ypos>120){ 
            sH.style.opacity=1;
            sH.style.transition="3s";
        };
            sH6.style.opacity=0;
            if(ypos>200){ 
            sH6.style.opacity=1;
            sH6.style.transition="3s";
        };
            sIMG.style.opacity=0;
            if(ypos>320){ 
            sIMG.style.opacity=1;
            sIMG.style.transition="3s";
        };
            sH4.style.opacity=0;
            if(ypos>400){ 
            sH4.style.opacity=1;
            sH4.style.transition="3s";
        };
            sP.style.opacity=0;
            if(ypos>480){ 
            sP.style.opacity=1;
            sP.style.transition="3s";
        };

        };

     window.addEventListener("scroll",trigger);
    </script>

当我尝试修改“样式”时出现错误

Uncaught TypeError: Cannot set property 'opacity' of undefined

我发现那是节点列表,我试图添加 [0] 因为它是第一个元素,但没有成功。如何定义对象?

我通常使用 ID,但现在我有很多元素需要制作动画。

我是 javascript 的新手,我不知道如何使用 jQuery

最佳答案

document.querySelectorAll返回 NodeList ,你需要迭代它

因此,要获取第一个元素,您可以通过 [0]

sIMG[0].style

但是document.querySelector不返回 NodeList ,它返回第一个匹配的元素。在这里你不需要通过 [0]

获取第一个元素
sH[0].style.opacity=0;  
// ^-- error here

应该是:

sH.style.opacity=0; 

关于Javascript queryselector.style.modify "uncaught TypeError",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35871926/

相关文章:

javascript - React-router-modal 奇怪的行为 - 我需要点击两次才能返回,应该只有一次

javascript - 找不到模块 : Can't resolve 'style'

javascript - JavaScript中 "forEach(el => {})"和 "forEach(function(){})"有什么区别

javascript - 将属性添加到元素 Javascript

javascript - CasperJS scraper无法通过选择器检索内容

javascript - 试图从字符串中删除 'px' 吗?

javascript - jQuery 或 Ajax 仪表

css - Material 设计: Bootstrap 3 Responsive Navbar

css - NG-Bootstrap Navbar-动画汉堡动画

iphone - iPad 3(或新 iPad)上的 CSS 媒体查询