15 Cool JavaScript示例代码段

文章撰写者:
  • 推荐文章
  • 更新:Mar 06,2012

关于JavaScript的快速概述

JavaScript is used everywhere online these days – to improve website interactivity, to validate information, and/or to improve a website outlooks. JavaScript first appeared in 1995 and has come a long way since then in terms of being accepted and how it is used. The syntax used in JavaScript was strongly influenced by C; but Java, Pearl, Python, and Scheme also played its part too.

什么是JavaScript?

有一个旧的YouTube剪辑很好地回答了这个问题。 开始。

初学者提示:你需要知道什么?

首先,您需要了解的一些基础知识是:

  • JavaScript can be turned off in the browser
  • JavaScript will run each time a page is loaded
  • JavaScript takes time to load on a slow Internet connection
  • JavaScript is still ran from cached pages
  • You can host JavaScript within a web page or externally from a .js file
  • JavaScript is completely different than Java

It is also important to understand that JavaScript will actually lead to disaster when it’s used in a wrong way. Poorly configured and sloppy coded JavaScripts will slow your website and damage the overall site navigation. This in turn affect the return rate of your visitors (due to bad user experience) as well as search engine rankings (due to slow website response rates). To help validate my case here, put yourself in the shoes of a viewer. If a website you were visiting loaded slowly, was difficult to navigate, and in overall, unappealing – would you return to the site? I wouldn’t.

Below is a small list of things to think about when adding JavaScript to your website.

  • Is JavaScript required for the site to function properly?
  • What will the site look like if the JavaScript was blocked?
  • Will the JavaScript harm the server performance?
  • Will adding the JavaScript help move your site in the direction you want it to go?

No, I am not trying to scare you away with these points. In fact, don’t be afraid to use JavaScript on your websites as it provides tons benefits and, as mentioned, it’s used by the majorities. The key point I am trying to get across here is don’t just keep adding JavaScript features to a site when they are unnecessary. Some sites are will need more JavaScript than the rest; some just need less – Just because one site is doing it doesn’t mean you should do the same.

Freebies: 15 Cool JavaScript Snippets For Your Website

JavaScript代码段

Now, let’s get down to the stuffs that you came here for – below is a list of 15 JavaScript snippets that will enhance your site in either functionality or appearance. The code will be broken down into two sections, the head and body or .js file. If no section title is given then it is not needed for that particular snippet.

Understanding HTML5 Video

快速样品

<script type="text/javascript">

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

if ( !understands_video() ) {
//必须是较旧的浏览器或IE。
// Maybe do something like hide custom
// HTML5控件。 管他呢…
videoControls.style.display = ‘none’;
}

</ SCRIPT>

JavaScript代码段的作用是什么?

This little snippet will prevent your website from trying to display a video that the browser cannot support, saving you bandwidth and processing power.

JavaScript Cookies

快速样品

<script type="text/javascript">

/ **

*设置具有给定名称和值的Cookie。

*

* name cookie的名称

* value cookie的值

* [expires] cookie的截止日期(默认值:当前会话结束)

* [path] cookie有效的路径(默认:调用文档的路径)

* [domain] cookie有效的域

*(默认:调用文档的域名)

* [secure]布尔值,指示cookie传输是否需要a

*安全传输

*/

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

document.cookie = name +“=”+ escape(value)+

((expires)?“; expires =”+ expires.toGMTString():“”)+

(?(路径)“;路径=”+路径:“”)+

((domain)?“; domain =”+ domain:“”)+

((安全)“安全”:“”);

}

</ SCRIPT>

<script type="text/javascript">

/ **

*获取指定cookie的值。

*

* name所需cookie的名称。

*

*返回包含指定cookie值的字符串,

*如果cookie不存在,则为null。

*/

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)返回null;

} {

开始+ = 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">

/ **

*删除指定的cookie。

*

* cookie的名称

* cookie的[path]路径(必须与用于创建cookie的路径相同)

* cookie的[域]域(必须与用于创建cookie的域相同)

*/

function deleteCookie(name,path,domain){

if(getCookie(name)){

document.cookie = name +“=”+

(?(路径)“;路径=”+路径:“”)+

((domain)?“; domain =”+ domain:“”)+

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

}

}

</ SCRIPT>

JavaScript代码段的作用是什么?

This snippet is a little long but very useful, it will allow your site to store information on the viewer’s computer then read it at another point in time. This snippet can be used in many different ways to accomplish different tasks.

Preload your images

快速样品

<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代码段的作用是什么?

This snippet will prevent your site from having that awkward time when it is only displaying part of the site; this not only looks bad but is also unprofessional. All you have to do is add your images to the preloadImages section and you are ready to roll.

E-mail Validation

快速样品

头:

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

身体:

<form onSubmit="return validateEmail(this);" action="">
电子邮件地址:
<input type="text" name="emailid" />
<input type="submit" value="Submit" />
<input type="reset" value="Reset" />
</ FORM>

JavaScript代码段的作用是什么?

This snippet will validate that a properly formatted E-mail address is entered in a form, it cannot guarantee that the E-mail address is real, there is no way to check for that with JavaScript.

No Right-Click

快速样品

<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;
}
其他{
document.onmouseup = f2;
document.oncontextmenu = f1;
}
document.oncontextmenu = new function("return false");
</ SCRIPT>

JavaScript代码段的作用是什么?

This snippet will prevent the viewer from being able to right-click on your page. This can discourage the average user from borrow images or code from your site.

显示随机引号

快速样品

:

<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);
文件撰写(引号[兰特]);
}
writeRandomQuote();
</ SCRIPT>

身体:

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

JavaScript代码段的作用是什么?

Ok so this is not a snippet that all sites would use but it can be used to display more than just random quotes. You can change the content ok the quotes to whatever you want and have random images or text displayed anywhere on your site.

Previous/Next Links

快速样品

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

JavaScript代码段的作用是什么?

This snippet is great if you have multiple pages on an article or tutorial. It will allow the user the browse between the pages with ease. It is also small and light weight from a resource point of view.

Bookmark a Page

快速样品

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

JavaScript代码段的作用是什么?

This snippet will allow the user to bookmark your page with ease; all they have to do is click the link. Its little features like this that can increase your viewers overall experience.

轻松打印页面链接

快速样品

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

JavaScript代码段的作用是什么?

This little link will allow your views to easily print your page. It utilizes the quick print feature already setup by your browser and utilizes no resources until it is clicked.

显示格式化日期

快速样品

:

<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>

身体:

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

JavaScript代码段的作用是什么?

This snippet will allow you to display the current date anywhere on your webpage and does not need to be updated. Simply put it in place and forget about it.

逗号分隔符

快速样品

:

<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;
文件撰写(下);
}
</ SCRIPT>

身体:

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

JavaScript代码段的作用是什么?

This snippet would be used mainly by sites that use numbers often. This snippet will keep your numbers looking the same across the board. All you have to do is copy the body line where you want to add a number and replace the number there with your number.

获取浏览器的显示区域

快速样品

<script type="text/javascript">

<! -

var viewportwidth;

var viewportheight;

//更符合标准的浏览器(mozilla / netscape / opera / IE7)使用window.innerWidth和window.innerHeight

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

{

viewportwidth = window.innerWidth,

viewportheight = window.innerHeight

}

//符合标准的IE6模式(即有效的doctype作为文档的第一行)

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

&& typeof document.documentElement.clientWidth!=

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

{

viewportwidth = document.documentElement.clientWidth,

viewportheight = document.documentElement.clientHeight

}

//旧版本的IE

其他

{

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

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

}

document.write('<p>您的视口宽度为'+ viewportwidth +'x'+ viewportheight +'</ p>');

/ / - >

</ SCRIPT>

JavaScript代码段的作用是什么?

This snippet will allow you to get the width and height of the display area in your views browser. This will give the designer the ability to create and use different displays based on the size of the user’s browser window.

Redirect with Optional Delay

快速样品

<script type="text/javascript">

setTimeout(“window.location.href =

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

</ SCRIPT>

JavaScript代码段的作用是什么?

This snippet will allow you to redirect your viewers to another page and it has the option of setting a delay. The use of this snippet is pretty self-explanatory and it is a very valuable tool to have in your belt.

Detect iPhones

样本

<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上,允许您向其显示不同的内容。 这个片段对于移动市场的规模来说是非常宝贵的,它只会继续增长。

Print Message to Status Bar

快速样品

<script language="javascript" type="text/javascript">
<! -
window.status =“<输入你的消息>”;
/ / - >
</ SCRIPT>

JavaScript代码段的作用是什么?

This little snippet will allow you to print a message to the status bar. You can display recent or important news in an area the will catch the eye of the user.

WHSR Guest的文章

本文由客座撰稿人撰写。 以下作者的观点完全是他或她自己的观点,可能无法反映WHSR的观点。