简体   繁体   English

如何将Javascript运行时间放在INPUT标记中

[英]How to put the Javascript running time in an INPUT tag

Credits to the person I get this Javascript code for running time (Cleared my history and forgot the site, so sorry.) Javascript code for getting time. 感谢我获得此Javascript代码以获取运行时间的人(清除了我的历史记录并忘记了该网站,所以很抱歉。)Javascript代码获得了时间。

<script type="text/javascript">
  function DisplayTime(){
    if (!document.all && !document.getElementById)
      return
    timeElement=document.getElementById? document.getElementById("mytime"): document.all.tick2
    var CurrentDate=new Date()
    var hours=CurrentDate.getHours()
    var minutes=CurrentDate.getMinutes()
    var seconds=CurrentDate.getSeconds()
    var DayNight="PM"
    if (hours<12) DayNight="AM";
    if (hours>12) hours=hours-12;
    if (hours==0) hours=12;
    if (minutes<=9) minutes="0"+minutes;
    if (seconds<=9) seconds="0"+seconds;
    var currentTime=hours+":"+minutes+":"+seconds+" "+DayNight;
    timeElement.innerHTML="<font style='font-family:verdana, arial,tahoma;font- size:12px;color:#E25984; font-weight:bold;'>"+currentTime+"</b>"
    setTimeout("DisplayTime()",1000)
  }
  window.onload=DisplayTime
</script>

My form: 我的表格:

<form class="signin" method="POST" action="testVal.php">
  <span style="margin-top:15px; float:left;">Time</span>
  <input name="times" type="text" id="mytime" value="<?php echo $mytime ?>" />

The time is working but this is in PHP to get the time and needs to refresh. 时间在工作,但这是用PHP来获取时间,需要刷新。 What I want is a running time in Javascript that doesn't need to refresh and indeed it's working but only in <p> and <h1> tags (in what I tried). 我想要的是Javascript中的运行时间,无需刷新,并且确实可以运行,但是仅在<p><h1>标记中(按照我的尝试)。 It displays the time dynamically. 它动态显示时间。

<p>Current time:</p><p id="mytimes"><p>

Aside from the input tags I don't know how to display the javascript in HTML Input tag. 除了输入标签外,我不知道如何在HTML输入标签中显示javascript。 I tried some but it displays blank. 我尝试了一些,但显示空白。 I need it to be displayed in an INPUT tag for some reason. 由于某种原因,我需要将其显示在INPUT标签中。

Any revisions or suggestions will help. 任何修订或建议将有所帮助。

Your help will be greatly appreciated. 对你的帮助表示感谢。 Thanks. 谢谢。

For an input tag, the innerHtml attribute is improper. 对于输入标签, innerHtml属性不正确。 Use the value attribute instead: 改用value属性:

timeElement.value = currentTime;

If later on you wish to apply some styling, use CSS instead: 如果以后您希望应用某些样式,请改用CSS:

timeElement.style.fontWeight = 'bold';
timeElement.style.fontFamily = 'Verdana';
timeElement.style.fontSize = '12px';
timeElement.style.color = '#E25984';

The html: 的HTML:

<form class="signin" method="POST">
    <span style="margin-top:15px; float:left;">Time</span>
    <input name="times" type="text" id="mytime" value=""/>
</form>

The js: js:

window.onload=setInterval(
    function DisplayTime(){
        if (!document.all && !document.getElementById)
            return;
        timeElement=document.getElementById? document.getElementById("mytime"): document.all.tick2;
        var CurrentDate = new Date();
        var hours = CurrentDate.getHours();
        var minutes = CurrentDate.getMinutes();
        var seconds = CurrentDate.getSeconds();
        var DayNight = "PM";
        if (hours<12) DayNight = "AM";
        if (hours>12) hours = hours-12;
        if (hours===0) hours = 12;
        if (minutes<=9) minutes = "0"+minutes;
        if (seconds<=9) seconds = "0"+seconds;
        var currentTime = hours+":"+minutes+":"+seconds+" "+DayNight;
        timeElement.style.fontWeight = 'bold';
        timeElement.style.fontFamily = 'Verdana';
        timeElement.style.fontSize = '12px';
        timeElement.style.color = '#E25984';
        timeElement.value = currentTime;

    },1000);

The fiddle: 小提琴:

http://jsfiddle.net/dAcwu/1/ http://jsfiddle.net/dAcwu/1/

In your code: 在您的代码中:

> function DisplayTime(){

By convention, identifiers starting with a capital letter are reserved for constructors. 按照惯例,以大写字母开头的标识符保留给构造函数使用。 Plain functions names should start with a lower case letter. 普通函数名称应以小写字母开头。

>    if (!document.all && !document.getElementById)
>    return
>    timeElement=document.getElementById? document.getElementById("mytime"): document.all.tick2

I doubt that there are any browsers in use that require document.all , you can kill two birds with one stone doing: 我怀疑是否有正在使用的需要document.all的浏览器,您可以用一块石头杀死两只鸟:

    var timeElement = document.getElementById && document.getElementById("mytime");
    if (!timeElement) return;

.

>  var CurrentDate=new Date()

Note that variable names starting with a capital letter are, by convention, reserved for constructors. 请注意,按照惯例,以大写字母开头的变量名称保留给构造函数使用。 And since this variable is internal and it is quite clear that it's a date object, and the only date object in this function, consider making the name shorter for convenience: 并且由于此变量是内部变量,并且很明显它是一个日期对象,并且是此函数中唯一的日期对象,因此为方便起见,请考虑将名称缩短:

    var d = new Date(); 

.

> var hours=CurrentDate.getHours()
> var minutes=CurrentDate.getMinutes()
> var seconds=CurrentDate.getSeconds()
> var DayNight="PM"
> if (hours<12) DayNight="AM";
> if (hours>12) hours=hours-12;
> if (hours==0) hours=12;
> if (minutes<=9) minutes="0"+minutes;
> if (seconds<=9) seconds="0"+seconds;
> var currentTime=hours+":"+minutes+":"+seconds+" "+DayNight;

You can make all that a lot shorter with a small helper function to pad values and some handy operators and methods: 您可以使用小的辅助函数来填充值以及一些方便的运算符和方法,从而将所有内容简化很多:

function addZ(n){return (n<10? '0' : '') + n;}
var h = d.getHours();
var ampm = h < 12? 'AM' : 'PM';
h = h % 12 || 12;
var timeString = [addZ(h), addZ(d.getMinutes()), addZ(d.getSeconds())].join(':');

.

> timeElement.innerHTML="<font style='font-family:verdana, arial,tahoma;font- size:12px;color:#E25984; font-weight:bold;'>"+currentTime+"</b>"

All that styling should be applied to the containing element directly, and the HTML is invalid anyway (the font tag was deprecated in HTML 4 and is removed in HTML 5, tags are not balanced). 所有样式应直接应用于包含元素,并且HTML还是无效的(字体标记在HTML 4中已弃用,而在HTML 5中已删除,标记不平衡)。 Rather than replacing the innerHTML, you can provide a robust setText function to set the text content of an element (see below). 您可以提供一个功能强大的setText函数来设置元素的文本内容,而不是替换innerHTML(请参见下文)。

> setTimeout("DisplayTime()",1000)
> }

Don't pass a string to setTimeout , it is passed the Function constructor and is a slow and inefficient way to pass the function, just pass a reference. 不要将字符串传递给setTimeout ,而是将其传递给Function构造函数,这是一种传递函数的缓慢而低效的方式,只需传递一个引用即可。 Also, set the function to run just after the next full second. 另外,将功能设置为在下一整秒之后运行。 So the full function becomes: 因此完整功能变为:

// This looks long winded, but it provides a robust way to set
// the text content for any browser in use. Since this uses a
// function expression, it must be before any code that calls setText
var setText = (function() {
    var div = document.createElement('div');

    if (typeof div.textContent == 'string') {
      div = null;
      return function (el, s) {
        el.textContent = s;
      }
    } else if (typeof div.innerText == 'string') {
      div = null;
      return function (el, s) {
        el.innerText = s;
      }
    } else {
      div = null;
      return function (el, s) {
        while (el.firstChild) {
          el.removeChild(el.firstChild);
        }
        el.appendChild(document.createTextNode(s));
      }
    }
}());

function displayTime(){

    var timeElement = document.getElementById && document.getElementById("mytime");

    if (!timeElement) return;

    var d = new Date();
    function addZ(n){return (n<10? '0' : '') + n;}
    var h = d.getHours();
    var ampm = h < 12? 'AM' : 'PM';
    h = h % 12 || 12;
    var timeString = [addZ(h), addZ(d.getMinutes()), addZ(d.getSeconds())].join(':') + ' ' + ampm;
    if (typeof timeElement.textContent == 'string') {
      timeElement.textContent = timeString;
    } else if (typeof timeElement.innerText == 'string') {
      setText(timeElement, timeString);
    }

    // Schedule to run just after next full second
    setTimeout(displayTime, 1020 - d.getMilliseconds());
}

// Start when page loads
window.onload = displayTime; 

And the HTML: 和HTML:

<div id="mytime"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM