Django无法使用静态引用在外部js文件中加载svg文件



我需要从我的javascript代码加载svg文件,我包括在我的index.html。我理解jinja模板不能在js外部文件中使用。因此,作为一个解决方案,我存储在我的whiteLogo和我在js代码中使用的徽标变量相同。

但是当我运行服务器并在页面上滚动时,我得到错误,资源无法找到。

Not Found: /[object HTMLImageElement]
[04/May/2022 12:18:05] "GET /[object%20HTMLImageElement] HTTP/1.1" 404 2441

我哪里出错了,我是否正确加载徽标路径?

index . html

<script type="text/javascript">
var whiteLogo = "{% static "app/images/logo/white-logo.svg" %}";
var logo = "{% static "app/images/logo/logo.svg" %}";
</script>
<script src="{% static 'app/js/main.js' %}">></script>

main.js

window.onscroll = function () {
var header_navbar = document.querySelector(".navbar-area");
var sticky = header_navbar.offsetTop;
var logo = document.querySelector('.navbar-brand img')
if (window.pageYOffset > sticky) {
header_navbar.classList.add("sticky");
logo.src = logo;
} else {
header_navbar.classList.remove("sticky");
logo.src = whiteLogo;
}
// show or hide the back-top-top button
var backToTo = document.querySelector(".scroll-top");
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
backToTo.style.display = "flex";
} else {
backToTo.style.display = "none";
}
};

编辑:

尝试这个

js

if (window.pageYOffset > sticky) {
header_navbar.classList.add("sticky");
logo.src = logoFromIndex;
} else {
header_navbar.classList.remove("sticky");
logo.src = whiteLogoFromIndex;
}

index . html

<script type="text/javascript">
var whiteLogoFromIndex = {% static 'app/images/logo/white-logo.svg' %};
var logoFromIndex = {% static 'app/images/logo/logo.svg' %};
</script>

我们使用index.html中创建的变量logo赋值给javascript文件main.js

中创建的logo变量
var logo = document.querySelector('.navbar-brand img')

那是我犯的一个愚蠢的错误。

index . html

<script type="text/javascript">
var whiteLogoFromIndex = "{% static "app/images/logo/white-logo.svg" %}";
var logoFromIndex = "{% static "app/images/logo/logo.svg" %}";
</script>
<script src="{% static 'app/js/bootstrap.min.js' %}"></script>

main.js

window.onscroll = function () {
var header_navbar = document.querySelector(".navbar-area");
var sticky = header_navbar.offsetTop;
var logo = document.querySelector('.navbar-brand img')
if (window.pageYOffset > sticky) {
header_navbar.classList.add("sticky");
logo.src = logoFromIndex;
} else {
header_navbar.classList.remove("sticky");
logo.src = whiteLogoFromIndex;
}
// show or hide the back-top-top button
var backToTo = document.querySelector(".scroll-top");
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
backToTo.style.display = "flex";
} else {
backToTo.style.display = "none";
}
};

相关内容

  • 没有找到相关文章