適用於您網站的15免費JavaScript示例片段

JavaScript是 這些天在網上無處不在 –改善網站互動性,驗證信息和/或改善網站前景。

JavaScript最早出現在1995中,從那時起,在接受度和使用方式上已經走了很長一段路。 JavaScript中使用的語法受到C語言的強烈影響; 但是Java,Pearl,Python和Scheme也發揮了作用。

JavaScrip初學者提示:您需要了解什麼?

首先,您需要了解的一些基礎知識是:

  • 可以在瀏覽器中關閉JavaScript
  • 每次加載頁面時都會運行JavaScript
  • JavaScript需要時間來加載慢速Internet連接
  • JavaScript仍然來自緩存頁面
  • 您可以在網頁中或從.js文件外部託管JavaScript
  • JavaScript與Java完全不同

同樣重要的是要了解,如果以錯誤的方式使用JavaScript,實際上會導致災難。

配置不當和草率的JavaScript會降低您的網站速度,並損害整個網站的導航。 反過來,這會影響訪問者的返回率(由於不良的用戶體驗)以及搜索引擎排名(由於網站響應率降低和漫遊器爬行)。 為了在這裡驗證我的案子,請讓自己成為觀眾。 如果您訪問的網站加載緩慢,導航困難,並且總體上沒有吸引力,您是否會返回該網站? 我不會

以下是向其中添加JavaScript時要考慮的一小件事 你的網頁.

  • 網站是否需要JavaScript才能正常運行?
  • 如果JavaScript被阻止,網站會是什麼樣子?
  • JavaScript會損害服務器性能嗎?
  • 添加JavaScript幫助會將您的網站移動到您想要的方向嗎?

不,我不是要嚇these這些觀點。

實際上,不要害怕 在您的網站上使用JavaScript 因為它提供了很多好處,並且如上所述,大多數人都在使用它。 我試圖在這裡講解的重點是不要在不必要的時候繼續向站點添加JavaScript功能。 有些網站比其他網站需要更多的JavaScript; 有些只需要更少的資源–僅因為一個站點正在這樣做並不意味著您應該這樣做。

免費贈品:15 Cool JavaScript Snippets為您的網站

現在,讓我們來看看您到這裡來的東西-以下是15個JavaScript代碼段的列表,這些代碼段將在功能或外觀上增強您的網站。 該代碼將分為兩部分,head和body或.js文件。 如果沒有給出節標題,則不需要該特定代碼段。

1。 了解HTML5視頻

快速樣品

<script type="text/javascript">

function understands_video() {
return !!document.createElement('video').canPlayType; // boolean
}

if ( !understands_video() ) {
// Must be older browser or IE.
// Maybe do something like hide custom
// HTML5 controls. Or whatever...
videoControls.style.display = 'none';
}

</script>

JavaScript代碼段的作用是什麼?

這個小小的代碼片段會阻止您的網站嘗試顯示瀏覽器無法支持的視頻,從而節省帶寬和處理能力。

2。 JavaScript Cookies

快速樣品

<script type="text/javascript">

/**

* Sets a Cookie with the given name and value.

*

* name       Name of the cookie

* value      Value of the cookie

* [expires]  Expiration date of the cookie (default: end of current session)

* [path]     Path where the cookie is valid (default: path of calling document)

* [domain]   Domain where the cookie is valid

*              (default: domain of calling document)

* [secure]   Boolean value indicating if the cookie transmission requires a

*              secure transmission

*/                        

function setCookie(name, value, expires, path, domain, secure) {

    document.cookie= name + "=" + escape(value) +

        ((expires) ? "; expires=" + expires.toGMTString() : "") +

        ((path) ? "; path=" + path : "") +

        ((domain) ? "; domain=" + domain : "") +

        ((secure) ? "; secure" : "");

}

</script>




<script type="text/javascript">

/**

* Gets the value of the specified cookie.

*

* name  Name of the desired cookie.

*

* Returns a string containing value of specified cookie,

*   or null if cookie does not exist.

*/

function getCookie(name) {

    var dc = document.cookie;

    var prefix = name + "=";

    var begin = dc.indexOf("; " + prefix);

    if (begin == -1) {

        begin = dc.indexOf(prefix);

        if (begin != 0) return null;

    } else {

        begin += 2;

    }

    var end = document.cookie.indexOf(";", begin);

    if (end == -1) {

        end = dc.length;

    }

    return unescape(dc.substring(begin + prefix.length, end));

}

</script>




<script type="text/javascript">

/**

* Deletes the specified cookie.

*

* name      name of the cookie

* [path]    path of the cookie (must be same as path used to create cookie)

* [domain]  domain of the cookie (must be same as domain used to create cookie)

*/

function deleteCookie(name, path, domain) {

    if (getCookie(name)) {

        document.cookie = name + "=" +

            ((path) ? "; path=" + path : "") +

            ((domain) ? "; domain=" + domain : "") +

            "; expires=Thu, 01-Jan-70 00:00:01 GMT";

    }

}

</script>

JavaScript代碼段的作用是什麼?

這個片段有點長但非常有用,它允許您的網站在查看者的計算機上存儲信息,然後在另一個時間點讀取它。 此代碼段可以以多種不同方式使用,以完成不同的任務。

3。 預加載圖片

快速樣品

<script type="text/javascript">

var images = new Array();

function preloadImages(){

    for (i=0; i < preloadImages.arguments.length; i++){

         images[i] = new Image();

        images[i].src = preloadImages.arguments[i];

    }

}

preloadImages("logo.jpg", "main_bg.jpg", "body_bg.jpg", "header_bg.jpg");

</script>

JavaScript代碼段的作用是什麼?

此代碼段將阻止您的網站在僅顯示網站的一部分時遇到尷尬的時間; 這不僅看起來很糟糕,而且也是不專業的。 您所要做的就是將圖像添加到preloadImages部分,然後就可以滾動了。

4。 電子郵件驗證

快速樣品

Head:

<script type="text/javascript">
function validateEmail(theForm) {
if (/^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,3})+$/.test(theForm.email-id.value)){
return(true);
}
alert("Invalid e-mail address! Please enter again carefully!.");
return(false);
}
</script>

Body:

<form onSubmit="return validateEmail(this);" action="">
E-mail Address:
<input type="text" name="emailid" />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</form>

JavaScript代碼段的作用是什麼?

此代碼段將驗證是否以表格形式輸入了格式正確的電子郵件地址,它不能保證該電子郵件地址是真實的,因此無法使用JavaScript進行檢查。

5。 沒有右鍵單擊

快速樣品

<script type="text/javascript">
function f1() {
  if(document.all) { return false; }
}
function f2(e) {
  if(document.layers || (document.getElementById &! document.all)) {
    if(e.which==2 || e.which==3) { return false; }
  }
}
if(document.layers) {
  document.captureEvents(Event.MOUSEDOWN);
  document.onmousedown = f1;
}
else {
  document.onmouseup = f2;
  document.oncontextmenu = f1;
}
document.oncontextmenu = new function("return false");
</script>

JavaScript代碼段的作用是什麼?

此代碼段會阻止觀看者右鍵單擊您的頁面。 這可以阻止普通用戶從您的網站借用圖片或代碼。

6。 顯示隨機報價

快速樣品

Head:

<script type="text/javascript">
  writeRandomQuote = function () {
    var quotes = new Array();
    quotes[0] = "Action is the real measure of intelligence.";
    quotes[1] = "Baseball has the great advantage over cricket of being sooner ended.";
    quotes[2] = "Every goal, every action, every thought, every feeling one experiences, whether it be consciously or unconsciously known, is an attempt to increase one's level of peace of mind.";
    quotes[3] = "A good head and a good heart are always a formidable combination.";
    var rand = Math.floor(Math.random()*quotes.length);
    document.write(quotes[rand]);
  }
  writeRandomQuote();
</script>

Body:

<script type="text/javascript">writeRandomQuote();</script>

JavaScript代碼段的作用是什麼?

好的,所以這不是所有網站都會使用的片段,但它可以用來顯示不僅僅是隨機引號。 您可以將引號的內容更改為您想要的任何內容,並在您的網站上的任何位置顯示隨機圖像或文本。

7。 上一個/下一個鏈接

快速樣品

<a href="javascript:history.back(1)">Previous Page</a> | <a href="javascript:history.back(-1)">Next Page</a>

JavaScript代碼段的作用是什麼?

如果您在文章或教程中有多個頁面,則此片段非常有用。 它將允許用戶輕鬆瀏覽頁面。 從資源的角度來看,它也很小,重量輕。

8。 為頁面添加書籤

快速樣品

<a href="javascript:window.external.AddFavorite('http://www.yoursite.com', 'Your Site Name')">Add to Favorites</a>

JavaScript代碼段的作用是什麼?

此代碼段將允許用戶輕鬆為您的頁面添加書籤; 他們只需點擊鏈接即可。 它的小功能可以增加觀眾的整體體驗。

9。 輕鬆打印頁面鏈接

快速樣品

<a href="javascript:window.print();">Print Page</a>

JavaScript代碼段的作用是什麼?

這個小鏈接將允許您的視圖輕鬆打印您的頁面。 它利用瀏覽器已經設置的快速打印功能,在點擊之前不使用任何資源。

10。 顯示格式化日期

快速樣品

Head:

<script type="text/javascript">
  function showDate() {
    var d = new Date();
    var curr_date = d.getDate();
    var curr_month = d.getMonth() + 1; //months are zero based
    var curr_year = d.getFullYear();
    document.write(curr_date + "-" + curr_month + "-" + curr_year);
  }
</script>

Body:

<script type="text/javascript">showDate();</script>

JavaScript代碼段的作用是什麼?

此代碼段允許您在網頁上的任意位置顯示當前日期,而無需更新。 簡單地把它放在適當的位置並忘記它。

11。 逗號分隔符

快速樣品

Head:

<script type="text/javascript">
function addCommas(num) {
  num += '';
  var n1 = num.split('.');
  var n2 = n1[0];
  var n3 = n1.length > 1 ? '.' + n1[1] : '';
  var temp = /(d+)(d{3})/;
  while (temp.test(n2)) {
    n2 = n2.replace(temp, '' + ',' + '');
  }
  var out = return n2 + n3;
  document.write(out);
}
</script>

Body:

<script type="text/javascript">addCommas("4550989023");</script>

JavaScript代碼段的作用是什麼?

此代碼段主要用於經常使用數字的網站。 這個片段將使您的數字保持全面相同。 您所要做的就是複制要添加號碼的正文行,並將號碼替換為您的號碼。

12。 獲取瀏覽器的顯示區域

快速樣品

<script type="text/javascript">

<!--

var viewportwidth;

var viewportheight;

// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

if (typeof window.innerWidth != 'undefined')

{

      viewportwidth = window.innerWidth,

      viewportheight = window.innerHeight

}

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

else if (typeof document.documentElement != 'undefined'

     && typeof document.documentElement.clientWidth !=

     'undefined' && document.documentElement.clientWidth != 0)

{

       viewportwidth = document.documentElement.clientWidth,

       viewportheight = document.documentElement.clientHeight

}

// older versions of IE

else

{

       viewportwidth = document.getElementsByTagName('body')[0].clientWidth,

       viewportheight = document.getElementsByTagName('body')[0].clientHeight

}

document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>');

//-->

</script>

JavaScript代碼段的作用是什麼?

此代碼段允許您在視圖瀏覽器中獲取顯示區域的寬度和高度。 這將使設計人員能夠根據用戶瀏覽器窗口的大小創建和使用不同的顯示。

13。 重定向與可選延遲

快速樣品

<script type="text/javascript">

setTimeout( "window.location.href =

'http://walkerwines.com.au/'", 5*1000 );

</script>

JavaScript代碼段的作用是什麼?

此代碼段允許您將查看者重定向到另一個頁面,並且可以選擇設置延遲。 這個片段的使用非常明顯,它是一個非常有價值的工具。

14。 檢測iPhone

樣本

<script type="text/javascript">

if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {

    if (document.cookie.indexOf("iphone_redirect=false") == -1) {

        window.location = "http://m.espn.go.com/wireless/?iphone&i=COMR";

    }

}

</script>

JavaScript代碼段的作用是什麼?

此代碼段允許您檢測您的查看器是否在iPhone或iPod上,允許您向其顯示不同的內容。 這個片段對於移動市場的規模來說是非常寶貴的,它只會繼續增長。

15。 將消息打印到狀態欄

快速樣品

<script language="javascript" type="text/javascript"> 
<!-- 
   window.status = "<TYPE YOUR MESSAGE>"; 
// --> 
</script>

JavaScript代碼段的作用是什麼?

這個小片段將允許您將消息打印到狀態欄。 您可以在將吸引用戶眼球的區域中顯示最近或重要的新聞。

閱讀更多:

作者照片

WHSR 嘉賓的文章