jsfiddle代码无法在我的网站上运行

时间:2014-03-13 16:57:05

标签: javascript jquery html css

HTML:

<div id="container">
<div id="bar">
</div>
</div>

CSS:

#container {
width: 20px;
height: 150px;
position: relative;

}
#bar {
width: 100%;
height: 100%;
background-color: red;
position: absolute;
bottom: 0px;
}

JS:

function Bar(element) {
this.barEl = element;
this.progress = 100;
}

Bar.prototype.setProgress = function (p) {
if(p >= 0) {
    this.progress = p;
    this.barEl.style.height = this.progress + "%";
}
}

var barObj = new Bar(document.getElementById('bar'));
setInterval(function () {
barObj.setProgress(barObj.progress - 10);
}, 1000);

当我复制粘贴代码时,来自jsfiddle http://jsfiddle.net/Mp7R3/的代码无效,但它在jsfiddle上运行正常。可能我有一些onLoad问题,但我不知道如何解决它。我尝试了$(document).ready(function()但它没有帮助。

1 个答案:

答案 0 :(得分:1)

请确保您不要忘记在代码<head>中调用jQuery的脚本:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

您也可以尝试将代码放在代码的底部,这样只有在加载完整页面时它才能运行。

我还在最简单的页面下面写了这个代码(通常你应该分开HTML,CSS和JS),所以你可以把它与你自己的代码进行比较:

<!DOCTYPE html>
<html>
    <head>
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

        <title>- That's Work!!! -</title>

        <style>

        #container {
            width: 20px;
            height: 150px;
            position: relative;   
        }

        #bar {
            width: 100%;
            height: 100%;
            background-color: red;
            position: absolute;
            bottom: 0px;
        }

        </style>

    </head>
    <body>
        <div id="container">
            <div id="bar">
            </div>
        </div>
    </body>

    <script type="text/javascript">
        function Bar(element) {
            this.barEl = element;
            this.progress = 100;
        }

        Bar.prototype.setProgress = function (p) {
            if(p >= 0) {
                this.progress = p;
                this.barEl.style.height = this.progress + "%";
            }
        }

        var barObj = new Bar(document.getElementById('bar'));
        setInterval(function () {
                barObj.setProgress(barObj.progress - 10);
        }, 1000);

    </script>
</html>

我希望它会对你有所帮助!