【try..catch..】【判断输入是否为空】【onchange事件】【onmouseover和onmouseout事件】【onmousedown和onmouseup事件】

1.try..catch..

<body>
<script>
function myFunction()
{
try
{
var x=document.getElementById("demo").value;//取值
if(x=="")    throw "值为空";                //返回错误提示
if(isNaN(x)) throw "不是数字";
if(x>10)     throw "太大";
if(x<5)      throw "太小";
}
catch(e)                      //定义错误提示为e
{
var y=document.getElementById("mess");  //读取显示错误提示的标签id
y.innerHTML="错误:" + e + "。";      //通过e显示错误提示
}
}
</script>
<h1>我的第一个 JavaScript 程序</h1>
<p>请输入 5 到 10 之间的数字:</p>
<input id="demo" type="text">              <!--输入值-->
<button type="button" onclick="myFunction()">测试输入值</button><!--点击事件-->
<p id="mess"></p>                            <!--显示错误提示-->
</body>

显示结果:

 2.判断输入是否为空

<head>

function validate_required(field,alerttxt)//参数为 id/name 和 提示的消息
{
with (field)                         //定位到id
  {
      if (value==null||value=="")    //判断这个id的值是否为空
         {
             alert(alerttxt);         //若是,提示消息并返回false
             return false;
         }
      else {return true}             //若否,返回ture
  }
}

function validate_form(thisform)
{
with (thisform)                 //定为到form
  {
  if (validate_required(email,"请填写内容")==false) //给指定的id和提示信息
    {
        email.focus();                             
        return false;
    }
  }
}
</script>

</head>
    
<body>
       <form action="" onsubmit="return validate_form(this)" method="post"> <!--接收返回值判断是否提交数据-->
            Email: <input type="text" id="email" size="30">  <!--指定id或者name-->
            <input type="submit" value="Submit">   <!--提交按钮-->
       </form>

</body>

 3.onchange事件,输入文档的字母自动变成大写字母

<script>
function myFunction()
{
var x=document.getElementById("fname");
x.value=x.value.toUpperCase();
}
</script>

<body>
请输入英文字符:<input type="text" id="fname" onchange="myFunction()">
<p>当您离开输入字段时,会触发将输入文本转换为大写的函数。

</body>

4.onmouseover和onmouseout鼠标滑动触发事件

<script>
function mOver(obj)
{
obj.innerHTML="谢谢"
}

function mOut(obj)
{
obj.innerHTML="把鼠标移到上面"
}
</script>

<body>

<div onmouseover="mOver(this)" onmouseout="mOut(this)" style="120px;height:20px;padding:40px;color:#ffffff;">把鼠标移到上面</div>

</body>

5.onmousedown和onmouseup鼠标按住div事件

<script>
function mDown(obj)
{
obj.style.backgroundColor="#1ec5e5";
obj.innerHTML="请释放鼠标按钮"
}

function mUp(obj)
{
obj.style.backgroundColor="green";
obj.innerHTML="请按下鼠标按钮"
}
</script>

<body>

<div onmousedown="mDown(this)" onmouseup="mUp(this)" style="color:#ffffff;90px;height:20px;padding:40px;font-size:12px;">这里文字无法显示,因为鼠标没有按住这个div会触发onmouseup事件</div>

</body>

原文地址:https://www.cnblogs.com/wskxy/p/6659146.html