作者:Ei Sabai
翻译:Terry li - GBin1.com
英文:
10 most useful Javascript snippets from snipplr
下面的代码片段来自snipplr,一个代码片段库。他们都是用纯javascript书写的,没有实用任何javascript类库,比如,jQuery,Mootools,或者Dojo。
function checkMail(email){
var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (filter.test(email)) {
return true;
}
return false;
}
<script type="text/javascript">
function toggle_checkboxes(id) {
if (!document.getElementById){ return; }
if (!document.getElementsByTagName){ return; }
var inputs = document.getElementById(id).getElementsByTagName("input");
for(var x=0; x < inputs.length; x++) {
if (inputs[x].type == 'checkbox'){
inputs[x].checked = !inputs[x].checked;
}
}
}
</script>
<div id="parent_box">
<input type="checkbox" name="foo" value="1" /> 1<br/>
<input type="checkbox" name="foo" value="2" checked="checked" /> 2<br/>
<input type="checkbox" name="foo" value="3" checked="checked" /> 3<br/>
<br/>
<input type="button" value="Toggle checkboxes"
onclick="toggle_checkboxes('parent_box')" />
</div>
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");
4. javascript cookies设置 Source
/**
* 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" : "");
}
/**
* 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));
}
/**
* 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";
}
}
function sortList(id) {
var obj = document.getElementById("id");
var values = new Array();
for(var i = 0; i < obj.options.length; i++) {
values.push(obj.options[i].innerHTML + "--xx--" + obj.options[i].value);
}
values = values.sort();
for(var i = 0; i < values.length; i++) {
valueArray = values[i].split('--xx--');
obj.options[i].innerHTML = valueArray[0];
obj.options[i].value = valueArray[1];
}
}
function sortList(id) {
var obj = document.getElementById("id");
var values = new Array();
for(var i = 0; i < obj.options.length; i++) {
values.push(obj.options[i].innerHTML + "--xx--" + obj.options[i].value);
}
values = values.sort();
for(var i = 0; i < values.length; i++) {
valueArray = values[i].split('--xx--');
obj.options[i].innerHTML = valueArray[0];
obj.options[i].value = valueArray[1];
}
}
function sortList(id) {
var obj = document.getElementById("id");
var values = new Array();
for(var i = 0; i < obj.options.length; i++) {
values.push(obj.options[i].innerHTML + "--xx--" + obj.options[i].value);
}
values = values.sort();
for(var i = 0; i < values.length; i++) {
valueArray = values[i].split('--xx--');
obj.options[i].innerHTML = valueArray[0];
obj.options[i].value = valueArray[1];
}
}
6. 检测浏览器是否支持HTML5 video
Source
// Check if the browser understands the video element.
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';
}
7. 得到浏览器的viewport宽度和高度 Source
<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>
8. 由class名字取得对象元素 Source
/*
Written by Jonathan Snook, http://www.snook.ca/jonathan
Add-ons by Robert Nyman, http://www.robertnyman.com
*/
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/-/g, "-");
var oRegExp = new RegExp("(^|s)" + strClassName + "(s|$)");
var oElement;
for(var i=0; i<arrElements.length; i++){
oElement = arrElements[i];
if(oRegExp.test(oElement.className)){
arrReturnElements.push(oElement);
}
}
return (arrReturnElements)
}
/*
Written by Jonathan Snook, http://www.snook.ca/jonathan
Add-ons by Robert Nyman, http://www.robertnyman.com
*/
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/-/g, "-");
var oRegExp = new RegExp("(^|s)" + strClassName + "(s|$)");
var oElement;
for(var i=0; i<arrElements.length; i++){
oElement = arrElements[i];
if(oRegExp.test(oElement.className)){
arrReturnElements.push(oElement);
}
}
return (arrReturnElements)
}
setTimeout( "window.location.href="http://walkerwines.com.au/'", 5*1000 );
10. iphone类型的方向变化效果
Source
window.addEventListener('load', setOrientation, false);
window.addEventListener('orientationchange', setOrientation, false);
function setOrientation() {
var orient = Math.abs(window.orientation) === 90 ? 'landscape' : 'portrait';
var cl = document.body.className;
cl = cl.replace(/portrait|landscape/, orient);
document.body.className = cl;
}
原文出处:来自snipplr的10个最实用的javascript代码片段
分享到:
相关推荐
4. **Snipplr** - Snipplr 是一个源代码片段分享社区,专注于编程技巧和小段代码,如CSS Hack、JavaScript效果等。它支持分类、标签、搜索、评论和收藏功能,方便开发者找到并保存实用的代码片段。 5. **DZone ...
4. **Snipplr** - Snipplr是一个专注于分享编程技巧的社区,主要关注小型代码片段,如CSS hack、JavaScript效果代码等。该平台提供分类、标签、搜索、评论和收藏等功能,方便开发者快速查找和学习代码片段。 5. **...
- Snipplr是一个面向编程技巧和代码片段分享的社区,特别适合寻找JavaScript、CSS等小型代码解决方案。用户可以按类别和标签浏览、搜索、评论和收藏代码。 5. **DZone Snippets**: - DZone Snippets拥有大量用户...
5. **Snipplr**:Snipplr 是一个代码技巧分享社区,专注于小型代码片段,如 CSS Hack、JavaScript 特效等。通过分类、标签、搜索、评论和收藏等功能,方便用户发现和存储有用的代码片段。 6. **DZone Snippets**:...
4. **Snipplr**:这是一个分享代码技巧的社区,专注于编程中的小技巧和代码段,例如 CSS Hack、JavaScript 功能等。它提供了分类、标签、搜索、评论和收藏等功能,方便开发者查找和分享代码片段。 5. **DZone ...
- **专用的片段管理工具**:如Snippet或Snipplr,这些工具可以帮助管理和分享代码片段。 - **版本控制系统**:使用Git等工具可以更好地管理代码库,方便团队协作。 #### 三、使用正确的工具 选择合适的工具对于...
10. **Snipplr**:代码片段管理平台,方便存储和分享代码。 11. **ErrorKey**:专门针对错误代码的搜索引擎,解决调试难题。 12. **findJAR.com**:JAR文件搜索引擎,便于Java开发者查找库。 13. **github**:集成了...
jQuery Labs、Snippet Library、The Javascript Source、roScripts (beta)、Snipplr、Code Sucks、HTML Goodies、WebResources Depot、Ajax Rain 和 Open Source Scripts 等网站提供了大量预设的代码片段和教程,可...