[英]JS Text Loop with Previous, Pause & Next Button
I have the below code with me for Text with Next & Previous Button. 我下面的代码带有下一个和上一个按钮的文本。 I want this to loop repeatedly on page load and one button for pause in between the both. 我希望它在页面加载和一个按钮在两者之间暂停时反复循环。 All three buttons to be totally on the right side on the same line of displaying the text. 这三个按钮全部位于显示文本的同一行的右侧。 Please support me.. thanks... 请支持我..谢谢...
<!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;
function nextMsg(direction) {
msgPtr = msgPtr + direction;
if (msgPtr < 0) { msgPtr = messages.length-1; }
if (msgPtr > messages.length-1) { msgPtr = 0; }
document.getElementById('msg').innerHTML = messages[msgPtr];
}
window.onload = function () {
nextMsg(0);
}
</script>
<style type="text/css">
em { color:orange; }
#msg {
font-family:monospace;
background-color:yellow;
font-size:1em;
width:890px;
border:1px dotted red;
overflow:hidden;}
</style>
</head>
<body>
<div id="msg"></div><br>
<button onclick="nextMsg(-1)"><</button>
<button onclick="nextMsg(-1)">||</button>
<button onclick="nextMsg(1)">></button>
</body>
</html>
One solution would be to call nextMsg() recursively like 一种解决方案是像这样递归调用nextMsg()
function nextMsg(direction){
//snip
nextMsg(direction);
}
I wrote a very quick proof of concept with jQuery that should be rewritten in a cleaner way: http://jsfiddle.net/5NUPn/5/ 我用jQuery写了一个非常快速的概念证明,应该以一种更简洁的方式重写它: http : //jsfiddle.net/5NUPn/5/
Now for displaying both your message and buttons on the same line you need to use float. 现在,为了在同一行上显示消息和按钮,您需要使用float。
#msg { float: left; }
Using 'setInterval(code,millisec)' function. 使用'setInterval(code,millisec)'函数。 So your code should look like something like this: 因此,您的代码应如下所示:
var msgPtr =0;
var set_interval_id;
function pause() {
clearInterval(set_interval_id)
}
function play() {
set_interval_id = setInterval(function() {
nextMsg(msgPtr);
msgPtr++;
}, 2000 /* how often to execute the code (2 sec) */);
}
window.onload = function () {
play();
}
...
<button onclick="nextMsg(-1)"><</button>
<button onclick="pause()">||</button>
<button onclick="nextMsg(1)">></button>
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.