gpt4 book ai didi

javascript - 谜团 "TypeError: navWrap.offset() is undefined"

转载 作者:行者123 更新时间:2023-12-03 05:20:13 29 4
gpt4 key购买 nike

我完全被这个问题困扰了,有人知道这个问题可能是什么吗?

我想要在自定义 js 文件(在 Wordpress 中)中添加的代码是:

var navWrap = jQuery('#sidebarnavWrap'),
nav = jQuery('#sidebarnav'),
startPosition = navWrap.offset().top,
stopPosition = jQuery('#footer-three').offset().top - nav.outerHeight();

jQuery(document).scroll(function () {
//stick nav to top of page
var y = jQuery(this).scrollTop()

if (y > startPosition) {
nav.addClass('sticky');
if (y > stopPosition) {
nav.css('top', stopPosition - y);
} else {
nav.css('top', 0);
}
} else {
nav.removeClass('sticky');
}
});

这段代码在 jsfiddle 中完美运行。然而,当在我的 WordPress 网站上使用时,控制台提到“TypeError: navWrap.offset(...) is undefined

http://jsfiddle.net/ykto7uu9/42/

各位专业人士知道是什么原因造成的吗?非常感谢。

额外信息:我的自定义 js 文件已经包含一个非常简单的工作 jQuery 代码来显示/隐藏文本(无冲突),并且我使用以下方法将脚本排入了functions.php中:

function my_javascripts() {
wp_enqueue_script( 'js.custom', '/wp-content/themes/mytheme-child/js/js.custom.js', array() );
}
add_action( 'wp_enqueue_scripts', 'my_javascripts', 1000 );

最佳答案

您正在页面头部加载 JS,并且没有等待就绪回调。代码触发时没有 sidebarnavWrap 元素。

将整个 JS 代码块包装在:

jQuery(document).ready(function() {

// CODE HERE

});

我还建议对您的入队脚本调用进行一些调整。

  1. 您正在使用 jQuery,因此将其定义为依赖项
  2. 将脚本移至页脚

更新版本:

wp_enqueue_script( 'js.custom', '/wp-content/themes/mytheme-child/js/js.custom.js', array( 'jquery' ), false, true );

https://developer.wordpress.org/reference/functions/wp_enqueue_script/

关于javascript - 谜团 "TypeError: navWrap.offset() is undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41417347/

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