1.首先是js文件,我將其命名爲alertMsg.js,使用的時候直接alertMsg("哈嘍"),就可以啦,js文件內容如下:
window.alertMsg = function(txt) {
var alertFram = document.createElement("DIV");
alertFram.id = "alertFram";
alertFram.style.position = "fixed";
alertFram.style.width = "100%";
alertFram.style.textAlign = "center";
alertFram.style.top = "40%";
alertFram.style.zIndex = "10001";
strHtml = " <span style=\"font-family: 微軟雅黑;display:inline-block;background:#333;color:#fff;padding:0 20px;line-height:36px;border-radius:6px; \">" + txt + "</span>";
alertFram.innerHTML = strHtml;
document.body.appendChild(alertFram);
setTimeout((function(){
alertFram.style.display="none";
}),2000);
};
2.在html中使用時,先加載js文件<script src="js/alertMsg.js"></script>,然後寫js語句這麼寫(html):
<script>
$(function(){
$("#loginBtn").click(function(){
if($("#loginPhone").val()==""){
alertMsg("請輸入手機號");
return false;
}
if($("#loginPhone").val()!=="" && !/^1[3|4|5|8]\d{9}$/.test($("#loginPhone").val())){
alertMsg("手機號格式不正確");
return false;
}
if($("#loginPsw").val()==""){
alertMsg("請輸入密碼");
return false;
}
if($("#loginPsw").val()!=="" && $("#loginPsw").val()!=="888888"){
alertMsg("賬號或密碼不正確");
return false;
}
})
})
</script>