如今,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 会帮助您的网站朝着您希望的方向发展吗?
不,我不是想用这些观点吓跑你。
事实上,不要害怕在您的网站上使用 JavaScript,因为它提供了大量的好处,并且如前所述,它被大多数人使用。 我在这里试图传达的关键点是,不要只是在不必要的时候继续向网站添加 JavaScript 功能。 有些网站需要比其他网站更多的 JavaScript; 有些只是需要更少 – 仅仅因为一个站点正在这样做并不意味着您应该这样做。
免费赠品:为您的网站提供 15 个很酷的 JavaScript 片段
现在,让我们来看看您来这里是为了什么——下面是 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 Cookie
快速样品
<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="https://www.webhostingsecretrevealed.net/blog/featured-articles/15-cool-javascript-sample-snippets/javascript:history.back(1)">Previous Page</a> | <a href="javascript:history.back(-1)">Next Page</a>
JavaScript 片段有什么作用?
如果您在一篇文章或教程中有多个页面,则此代码段非常有用。 它将允许用户轻松地在页面之间浏览。 从资源的角度来看,它也是小而轻的。
8. 为页面添加书签
快速样品
<a href="https://www.webhostingsecretrevealed.net/blog/featured-articles/15-cool-javascript-sample-snippets/javascript:window.external.AddFavorite("http://www.yoursite.com', 'Your Site Name')">Add to Favorites</a>
JavaScript 片段有什么作用?
该片段将允许用户轻松地为您的页面添加书签; 他们所要做的就是点击链接。 像这样的小功能可以增加观众的整体体验。
9. 简易打印页面链接
快速样品
<a href="https://www.webhostingsecretrevealed.net/blog/featured-articles/15-cool-javascript-sample-snippets/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 =...