JavaScript小技巧

出自 ProgWiki
前往: 導覽搜尋
  • 已下內容省略HTML的script標籤,如要在HTML中使用的話,請記得加上下列。
<script type="text/javascript">
//<![CDATA[
    //JavaScript程式碼
//]]>
</script>

反網站綁架

if (top.location != location)
  top.location.href = location.href;

視窗最大化

  • 用途:進入網頁後,遊覽器的視窗自動最大化。
版本1
self.moveTo(0,0);
self.resizeTo(screen.availWidth,screen.availHeight);
版本2
var scr_w = screen.availWidth;
var scr_h = screen.availHeight;
 
if (scr_w != window.width || scr_h != window.height) {
      window.resizeTo(scr_w, scr_h);
      window.moveTo(0, 0);
}

禁用滑鼠右鍵

  • 用途:避免遊覽者輕易的複製網頁,或看到網頁的原始檔內容。
//禁用滑鼠右鍵
function forbidRightMouse(evt)
{
    if (evt)
        evt.preventDefault();               //dom2的事件模型,主要針對firefox/sofari
    else
        window.event.returnValue = false;   //IE的事件模型
}
 
document.oncontextmenu = forbidRightMouse;//防止遊覽者使用滑鼠右鍵

動態參數的函數

function printList() {
  for (var i = 0; i < printList.arguments.length; ++i) {
    document.write(printList.arguments[i] + "<BR>")
}

網站加入網頁瀏覽器的書籤

 function CreateBookmarkLink() {
 title = "ProgWiki"; 
 url = "http://www.player.idv.tw/prog/";
	if (window.sidebar) {
		window.sidebar.addPanel(title, url,"");
	} else if( window.external ) {
		window.external.AddFavorite( url, title); }
	else if(window.opera && window.print) {
		return true; }
 }
 if (window.external) {
  document.write('<a href = "javascript:CreateBookmarkLink()");">書籤/我的最愛</a>'); 
  } else  if (window.sidebar) {
  document.write('<a href = "javascript:CreateBookmarkLink()");">書籤</a>'); 
 } else if (window.opera && window.print) {	
   document.write('<a href = "javascript:CreateBookmarkLink()");">加入書籤</a>');
 }

如何用javaScript關閉瀏覽器不出現詢問

window.opener=null;
window.open('','_self');
window.close();

分頁列印與預覽列印(IE專用)

  • 這是常用分頁列印,以及Web設定印表機,預覽列印,以及設定列印功能。
var tag = 'H1'; // 內定以標籤<H1>為分頁開頭 
function printpage(tag)
{ 
    var coll = document.all.tags(tag); 
    for (i=0; i<coll.length; i++)
    { 
        coll(i).style.pageBreakBefore = "always"; 
    } 
}
<object id="WebBrowser" width=0 height=0 classid="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object> 
<A HREF=# onclick="javascript:WebBrowser.ExecWB(6,1)">設定印表機</A> 
<A HREF=# onclick="javascript:WebBrowser.ExecWB(7,1)">預覽列印</A> 
<A HREF=# onclick="javascript:WebBrowser.ExecWB(8,1)">設定列印</A> 
<A HREF=# onclick="javascript:printpage('H1')">設定換頁列印</A> 
 
<H1>第一頁標題</H1> 
第一頁內文 
<BR> 
<H1>第二頁標題</H1> 
第二頁內文 
<BR>

複製到剪貼簿

IE+FireFox適用
//Copy to clipboard: ref http://forum.moztw.org/viewtopic.php?p=131407
function copyToClipboard(txt) 
{
    var copied = false;
     if(window.clipboardData) {
        window.clipboardData.clearData();
        window.clipboardData.setData("text", txt);
        copied = true;
     } else if (window.netscape) {
        try {
           netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        } catch (e) {
           alert("被瀏覽器拒絕!\n請在瀏覽器網址列輸入'about:config'\n,將'signed.applets.codebase_principal_support'設為'true'");
        }
        var clip = Components.classes['@mozilla.org/widget/clipboard;1']
        .createInstance(Components.interfaces.nsIClipboard);
        if (!clip)
           return;
        var trans = Components.classes['@mozilla.org/widget/transferable;1']
        .createInstance(Components.interfaces.nsITransferable);
        if (!trans)
           return;
        trans.addDataFlavor('text/unicode');
        var str = new Object();
        var len = new Object();
        var str = Components.classes["@mozilla.org/supports-string;1"]
        .createInstance(Components.interfaces.nsISupportsString);
        var copytext = txt;
        str.data = copytext;
        trans.setTransferData("text/unicode",str,copytext.length*2);
        var clipid = Components.interfaces.nsIClipboard;
        if (!clip)
           return false;
        clip.setData(trans,null,clipid.kGlobalClipboard);
        copied = true;
     }
     if (copied) alert('已經複製到您的剪貼簿中!');
     else alert("使用的瀏覽器不支援文字複製功能!");
}
IE專用(例如textarea物件)
function CopyToClipboard(obj)
{
  obj.focus();
  obj.select();
  document.execCommand('copy');
}
HTML5 Clipboard API(截至2013年6月,好像只有 Google Chrome 支援)

網頁瀏覽器的版本

function checkBrowser() {
    var appName = window.navigator.appName;
    var appVersion = window.navigator.appVersion;
    var strPlatform = window.navigator.platform;
    var appCodeName = window.navigator.appCodeName;
    var userAgent = window.navigator.userAgent;
 
    var BrowserName = ""
    var BrowserVersion = ""
 
    if (appVersion.indexOf("MSIE") != -1) {
        BrowserName = "Internet Explorer";
 
        var re = new RegExp("MSIE (\\S){1,16}\\b");
        var m = re.exec(userAgent);
        if (m != null) {
            BrowserVersion = m[0].replace("MSIE ", "");
        }
    }
    else if (appVersion.indexOf("Trident") != -1) { //for IE 11.x
        BrowserName = "Internet Explorer";
        var re = new RegExp("rv:(\\S){1,16}\\b");
        var m = re.exec(userAgent);
        if (m != null) {
            BrowserVersion = m[0].replace("rv:", "");
        }
    }
    else if ((appName.indexOf("Netscape") != -1) &&
                (appCodeName.indexOf("Mozilla") != -1) &&
                (userAgent.indexOf("Firefox") != -1)) {
        BrowserName = "Firefox";
 
        var re = new RegExp("Firefox/(\\S){1,16}\\b");
        var m = re.exec(userAgent);
        if (m != null) {
            BrowserVersion = m[0].replace("Firefox/", "");
        }
    }
    else if ((appName.indexOf("Opera") != -1) &&
                (appCodeName.indexOf("Mozilla") != -1) &&
                (userAgent.indexOf("Opera") != -1)) {
        BrowserName = "Opera";
 
        var re = new RegExp("Opera/(\\S){1,16}\\b");
        var m = re.exec(userAgent);
        if (m != null) {
            BrowserVersion = m[0].replace("Opera/", "");
        }
    }
    else if ((appName.indexOf("Netscape") != -1) &&
                (appCodeName.indexOf("Mozilla") != -1) &&
                (userAgent.indexOf("Chrome") != -1)) {
        BrowserName = "Chrome";
 
        var re = new RegExp("Chrome/(\\S){1,16}\\b");
        var m = re.exec(userAgent);
        if (m != null) {
            BrowserVersion = m[0].replace("Chrome/", "");
        }
    }
 
    return {Name: BrowserName, Ver: parseFloat(BrowserVersion), Platform: strPlatform};
}

遊覽器端依預設語系進行轉址

//以JavaScript解析URL, 取得表單GET模式的QueryString
function getURLParam(strParamName)
{
    var strReturn = "";
    var strHref = window.location.href;
    if ( strHref.indexOf("?") > -1 )
    {
        var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
        var aQueryString = strQueryString.split("&");
        for ( var iParam = 0; iParam < aQueryString.length; iParam++ )
        {
            if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1 )
            {
                var aParam = aQueryString[iParam].split("=");
                strReturn = aParam[1];
                break;
            }
        }
    }
    return unescape(strReturn);
} 
 
//取得遊覽器的預設語系
var strLang = "";
if (typeof window.navigator.browserLanguage != "undefined") {
    strLang = window.navigator.browserLanguage;    //IE7用
}
else if (typeof window.navigator.language != "undefined") {
{
    strLang = window.navigator.language;           //FireFox3用
}
 
//轉址(以維基百科為例) http://zh.wikipedia.org/w/index.php?title=Wikipedia:%E9%A6%96%E9%A1%B5&variant=zh-tw
var strTitle = getURLParam("title");
if ((strLang != "") && (strTitle != ""))
{
    var strUrl = "http://zh.wikipedia.org/w/index.php?title=" + escape(strTitle);
    strUrl = strUrl + "&variant=" + strLang;
    window.location.href = strUrl;
}

載入網頁到指定的頁框

  • GoToUrl(url)
  • GoToUrl(url, windowName)
  • GoToUrl(url, windowName, Options)
function GoToUrl()
{
	var arg = GoToUrl.arguments;
	if ((arg.length == 1) &&
	    (typeof arg[0] == "string"))
		this.location.href = arg[0];
	else if (arg.length == 2) &&
		(typeof arg[0] == "string") &&
		(typeof arg[1] == "string"))
		window.open(arg[0], arg[1], '');
	else if (arg.length == 3) &&
		(typeof arg[0] == "string") &&
		(typeof arg[1] == "string") &&
		(typeof arg[2] == "string"))
		window.open(arg[0], arg[1], arg[2]);
}

自動延展頁框高度

<iframe id="MainFrame" name="MainFrame" frameborder="0" width="800" style="min-height:620px"
        onload="FixMainFrameHeight('MainFrame')"></iframe>
function FixFrameHeight(id) {
        $('iframe#'+id).height(GetIFrameDocument(id).body.scrollHeight);
}

判斷Flash player是否已安裝

var hasFlash = false;
try {
  var fo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
  if(fo) hasFlash = true;
}catch(e){
  if(navigator.mimeTypes ["application/x-shockwave-flash"] != undefined) hasFlash = true;
}

取得指定年月的該月天數

function daysInMonth(month, year) {
    return new Date(year, month, 0).getDate();
}

中英混合的字串截斷不再有亂碼

function SubString(str, n) {
        var r = /[^\x00-\xff]/g;
        if (str.replace(r, "mm").length <= n) { return str; }
        var m = Math.floor(n / 2);
        for (var i = m; i < str.length; i++) {
            if (str.substr(0, i).replace(r, "mm").length >= n) {
                return str.substr(0, i) + "...";
            }
        }
        return str;
    }