JS文本循环按钮

时间:2013-02-28 08:46:20

标签: javascript html css

我以http://jsfiddle.net/5NUPn/5/的形式得到了我之前问题的答案,但是当我将代码放到我的普通html页面时,它的播放效果并不相同。请让我知道我犯了什么错误...

以下是我的HTML中的代码

<!DOC html>
<html>
<head>
<script type="text/javascript">
var messages = [
    'Messages for <em>kindergarden</em> class',
    'Message for <em>1st grade</em>',
    'Message for <em>2nd grade</em>',
    'Message for <em>3rd grade</em>',
    'Message for <em>4th grade</em>',
    'Message for <em>5th grade</em>',
    'Message for <em>6th grade</em>'
];

var msgPtr = 0;
var player;
function nextMsg(direction, loop) {
    msgPtr = msgPtr + direction;
    if (msgPtr < 0) { msgPtr = messages.length-1; }
    if (msgPtr > messages.length-1) { msgPtr = 0; }
    document.getElementById('msg').innerHTML = messages[msgPtr];
    if(loop){
        player = setTimeout(function(){ nextMsg(1, true); }, 1000);
    }
}
function toggleMsg()
{
    clearTimeout(player);
}
nextMsg(0, true);

$(function(){
    $('.prev').click(function(){
       clearTimeout(player);
        nextMsg(-1, false);
        $('.playpause').removeClass('playing').addClass('stopped').text('play');
    });
    $('.next').click(function(){
        clearTimeout(player);
        nextMsg(1, false);
        $('.playpause').removeClass('playing').addClass('stopped').text('play');
    });
    $('.playpause').click(function(){
       if($(this).hasClass('stopped'))
       {
           nextMsg(0, true);
           $(this).removeClass('stopped').addClass('playing').text('pause');
       }
        else
        {
            clearTimeout(player);
            $(this).removeClass('playing').addClass('stopped').text('play');
        }
    });
});
</script>


    <style type="text/css">
        em { color:orange; }
        #msg { 
            font-family:monospace; 
            background-color:yellow;
            font-size:1em; 
            border:1px dotted red; 
            overflow:hidden;
        /*float: left;*/
        }
        #buttons { /*float: right;*/ }
    </style>

</head>
<body>
    <div id="msg"></div>
    <div id="buttons">
        <button class="prev">&lt;</button>
        <button class="playpause playing">pause</button>
        <button class="next">&gt;</button>
    </div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

尝试将Javascript块移动到body元素的底部:

<html>
<head>
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <script src="http://code.jquery.com/jquery-migrate-1.1.1.min.js"></script>
</head>

<body>

  <!-- divs and buttons go here -->

<script>

  // Javascript goes here

</script>

</body>
</html>