javascript 未捕获的类型错误:无法读取 null 的属性“classList”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26970562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
uncaught TypeError: Cannot read property 'classList' of null
提问by user3182518
Hi Im trying to make a shrinking header, I almost have it working however i keep getting the above error for this section of the js files
嗨,我正在尝试缩小标题,我几乎可以正常工作,但是对于 js 文件的这一部分,我不断收到上述错误
var cbpAnimatedHeader = (function() {
var docElem = document.documentElement,
header = document.querySelector( '.cbp-af-header' ),
didScroll = false,
changeHeaderOn = 300;
function init() {
window.addEventListener( 'scroll', function( event ) {
if( !didScroll ) {
didScroll = true;
setTimeout( scrollPage, 250 );
}
}, false );
}
function scrollPage() {
var sy = scrollY();
if ( sy >= changeHeaderOn ) {
var windowtab = $(window).width();
if (windowtab >= 1021)
{
classie.add( header, 'cbp-af-header-shrink' );
}
}
else {
classie.remove( header, 'cbp-af-header-shrink' );
}
didScroll = false;
}
function scrollY() {
return window.pageYOffset || docElem.scrollTop;
}
init();
})();
and
和
var classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
I had it working in DNN when I add a module for the jQuery however when I had it to the skin, I end up with the above console error
当我为 jQuery 添加一个模块时,我让它在 DNN 中工作,但是当我将它添加到皮肤时,我最终遇到了上面的控制台错误
回答by Jai
This line in the script:
脚本中的这一行:
header = document.querySelector('.cbp-af-header')
@ MDN for document.querySelector()
@ MDN for document.querySelector()
it says that, the first element in the document with the class is returned.
它说,返回具有该类的文档中的第一个元素。
So may be you are looking for .querySelectorAll("selector/s")
:
那么您可能正在寻找.querySelectorAll("selector/s")
:
document.querySelectorAll(".cbp-af-header");
@ MDN for document.querySelectorAll()
@ MDN for document.querySelectorAll()
returns a listof all elements (div in case)supplied within the document.
返回文档中提供的所有元素(如果是 div)的列表。
回答by Elmuch
I encountered the same problem. I realized that IIFE was executed before the DOM was completely loaded. If you are use jQuery, try wrapping it in $(document).ready()
我遇到了同样的问题。我意识到 IIFE 是在 DOM 完全加载之前执行的。如果您使用 jQuery,请尝试将其包装在 $(document).ready() 中