[英]My code is working on codepen but not on my editor
我的代码在 codepen 上工作,但不在我的编辑器 (PyCharm) 上。 这是 django 项目的一部分。 不工作是指我得到一个空白页,没有 output(无文本)。 我希望看到一些无限滚动的文本出现在屏幕上
我试图阅读一些解决类似问题的答案,但这些解决方案似乎都不适合我/或者我没有正确应用它们。 专门添加完整的 URL 路径,用于通过 CDN 获取 ScrollWatch。 这是我的代码示例
html
{ % load script % }
<html lang="en">
<head>
<meta charset="UTF-8">
<title>The Gradient Boost</title>
<link rel="stylesheet" href="{% static 'second/css/app/book.css' %}">
<script src="https://cdn.jsdelivr.net/npm/scrollwatch@2.0.1/dist/ScrollWatch-2.0.1.min.js"></script>
</head>
<body>
<h2><div data-scroll-watch>First Text</div></h2>
<h2><div data-scroll-watch>Second Text</div></h2>
<h3><div data-scroll-watch>Third Text</div></h3>
<script src="{% static 'second/js/app/book.js' %}"></script>
</body>
</html>
css 位置 -> static\second\css\app\book.css
.watch-container {
font-size: 2em;
width: 75%;
height: 150px;
padding: 20px;
margin: 50px auto;
background-color: #0681CD;
color: #fff;
overflow: auto;
text-align: center;
}
div {
text-align: center;
font-size: 1em;
margin: 200px 0;
opacity: 0;
transition: opacity 1s;
font-weight: normal
}
div.scroll-watch-in-view {
opacity: 1;
}
和 javascript 位置 -> static\second\js\app\book.js
(function() {
var addElements = function() {
var txt = document.createTextNode('Testing');
var el;
el = document.createElement('div');
el.appendChild(txt);
document.body.appendChild(el);
// If we want newly injected elements to be watched, refresh ScrollWatch. It will re-query the dom and start watching new elements.
swInstance.refresh();
};
var swInstance = new ScrollWatch({
watch: 'div',
infiniteScroll: true,
infiniteOffset: 200,
onInfiniteYInView: addElements
});
})();
不知道我做错了什么?
这是我在浏览器控制台上收到的错误消息
Uncaught TypeError: Cannot read property 'appendChild' of null
at X.addElements (book.js:10)
at X.d (ScrollWatch-2.0.1.min.js:662)
at X.f (ScrollWatch-2.0.1.min.js:662)
at new X (ScrollWatch-2.0.1.min.js:662)
at book.js:17
at book.js:24
DevTools failed to parse SourceMap: chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/sourcemaps/onloadwff.js.map
DevTools failed to parse SourceMap: chrome-extension://hgmhmanijnjhaffoampdlllchpolkdnj/js/lib/purify.min.js.map
更新在输入console.log(el) 尝试找出为什么el 我收到null 返回后,我开始收到另一条错误消息:
book.js:13 Uncaught TypeError: Cannot read property 'refresh' of undefined
at X.addElements (book.js:13)
at X.d (ScrollWatch-2.0.1.min.js:662)
at X.f (ScrollWatch-2.0.1.min.js:662)
at X.S (ScrollWatch-2.0.1.min.js:662)
at ScrollWatch-2.0.1.min.js:662
addElements @ book.js:13
d @ ScrollWatch-2.0.1.min.js:662
f @ ScrollWatch-2.0.1.min.js:662
S @ ScrollWatch-2.0.1.min.js:662
(anonymous) @ ScrollWatch-2.0.1.min.js:662
您需要将脚本包装在document.onload()
或更好window.onload()
子句中:
window.onload = function() {
// your script here
}
这是因为在创建文档的<body>
时会读取您的脚本,因此如果body
尚未准备好,则当您的脚本运行时document.body
将为null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.