特殊JavaScript脚本:
1.禁用(恢复)href超级链接.
2.javascript中调用vbs对话框实现Confirm,可以显示Yes,No,还有各种图标,仅IE下有效.
3.限制上传文件类型为jpg.
4.限制离开当前页面,在离开时提示.仅限制窗口关闭或通过某个href超级链接离开.(页面刷新和地址栏改变时不提示)
demo.html如下:
<html>
<header>
<title>Demo for Javascript</title>
<script>
//禁用超级连接
function EnabledLink(flag)
{
var btlink=document.getElementById('linkconfirm');
if(btlink!=null)
{
btlink.disabled = !flag;
btlink.onclick = function() { return flag; };
btlink.style.cursor = flag ? "hand" : "text";
btlink.style.textDecoration = flag ? "" : "none";
btlink.title= flag ? "open other page" : "disabled";
}
}
//限制文件类型
function checktype(uploadfile)
{
var filepath = uploadfile.value
//文件类型错误标记,防止重复调用
var hd = document.getElementById('hdfileerror');
if (hd.value.length==0 && filepath.length > 0)
{
filepath = filepath.substring(filepath.lastIndexOf('.') + 1, filepath.length)
if (filepath != 'jpg' && filepath != 'jpeg')
{
hd.value = '1';
alert("Incorrect file type, only JPEG files allowed.")
//清空 For IE
if (!window.addEventListener)
{
uploadfile.outerHTML += '';
}
else
{
//其它
uploadfile.value = '';
}
hd.value = '';
}
}
}
//实现vbs调用,IE有效
function testconfirm()
{
var flag=false;
var strmsg='Does this Requirement still need to be filled?';
if(top.execScript!=null)
{
flag=vbsconfirm(strmsg)
}
else
{
flag=window.confirm(strmsg);
}
alert(flag);
}
//调用vbs对话框?
function vbsconfirm(str)
{
execScript("n=msgbox('" + str + "', vbYesNo+vbQuestion,'Confirmation')", "vbscript");
return (n == 6);
}
//限制用户离开
window.onbeforeunload = function()
{
var hdfConfirm = document.getElementById('hdexitpage');
//用户当前窗口时提示,刷新不提示
if( (event.clientX > document.body.clientWidth && event.clientY < 0 || event.altKey)
|| hdfConfirm.value.length > 0)
{
hdfConfirm.value = '';
return 'Confirm Exit Page?';
}
hdfConfirm.value = '';
}
//设置限制标记
function setExitFlag()
{
var hdfConfirm = document.getElementById('hdexitpage');
if (hdfConfirm.value.length == 0)
{
hdfConfirm.value = '1';
}
}
</script>
</header>
<body>
<input type="file" id="uploadfile" width="550px" onBlur="checktype(this)" size="50" οnchange="checktype(this)"/>
<input type="hidden" id="hdfileerror" />
<input type="button" value="test confirm" οnclick="testconfirm();" />
<a href="demo.html" id="linkconfirm" title="open other page" Target="_blank" οnclick="testconfirm();" >test</a>
<input type="button" value="Enable Link" οnclick="EnabledLink(true);" />
<input type="button" value="Disable Link" οnclick="EnabledLink(false);" />
<a href="demo2.html" id="linkconfirm" title="can exit page" >can exit page</a>
<a href="demo3.html" id="linkconfirm" title="not exit page" οnclick="setExitFlag();" >not exit page</a>
<input type="hidden" id="hdexitpage" />
</body>
</html>