如何修改下面的脚本,以便在DOM中没有“.fixit”元素时不会抛出错误?
function fixedHeaders() {
var el = jQuery('.fixit'),
offset = el.offset(),
elHeight = el.height(),
scrollTop = jQuery(window).scrollTop()
if (((offset.top + 400) < scrollTop - el.height())) {
el.addClass('fixedElement');
}
if (scrollTop === 0) {
el.removeClass('fixedElement');
}
}
jQuery(function() {
jQuery(window)
.scroll(fixedHeaders)
.trigger("scroll");
});
答案 0 :(得分:1)
从
开始if (!jQuery('.fixit').length) return;
答案 1 :(得分:0)
if ($('.fixit').length) {
var el = jQuery('.fixit'),
offset = el.offset(),
elHeight = el.height(),
scrollTop = jQuery(window).scrollTop()
if (((offset.top + 400) < scrollTop - el.height())) {
el.addClass('fixedElement');
}
if (scrollTop === 0) {
el.removeClass('fixedElement');
}
}