外部Javascript文件在HTML文件中不起作用

时间:2018-04-15 19:05:05

标签: javascript html5 css3

base.html文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    {% load static %}
    <link rel="stylesheet" type="text/css" href="{% static 'style/baseStyle.css' %}">
    <script src="{% static 'js/basejs.js' %}"></script>
    <title></title>
    <link rel="stylesheet" href="">
</head>
<body>
    <div class="top-container">
        <h1>Scroll Down</h1>
        <p>Scroll down to see the sticky effect.</p>
    </div>

    <div class="header" id="myHeader">
        <h2>Fixed Header</h2>
    </div>

    <div>
        <h1>Working CSS</h1>
        <h1>Working CSS</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
        <h1>Working</h1>
    </div>

</body>
</html>

baseStyle.css

.header{
    padding: 10px 15px;
    background-color: #2F4F4F; /*DarkSlateGray*/
    color: #D3D3D3; /*LightGray*/
}


.sticky{
    position: fixed;
    top: 0;
    width: 100%;
}

.top-container {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

basejs.js

window.onscroll = function() {fixedHeader()};

var header = document.getElementById("myHeader");
var sticky = header.offsetTop;


function fixedHeader(){
    if(window.pageYOffset >= sticky){
        header.classList.add("sticky");
    }
    else{
        header.classList.remove("sticky");
    }
}

我已将css和js文件正确地包含在html文件中。这不会使标题粘贴滚动。但是,如果我将basejs.js文件的代码放在base.html中,它可以正常工作。为什么外部js文件在这里不起作用?帮我解决这个问题。

先谢谢。

1 个答案:

答案 0 :(得分:0)

尝试包装你的js代码,使它在加载时执行,或者在body的底部添加脚本而不是在头部