前端工程师必备常用代码,相信大家会经常碰到:
1、如何显示或是删除input域中的默认值
//这段代码展示了在用户未输入值时,
//如何在文本类型的input域中保留
//一个默认值
wap_val = [];
$(".swap").each(function (i) {
wap_val[i] = $(this).val();
$(this).focusin(function () {
if ($(this).val() == swap_val[i]) {
$(this).val("");
}
}).focusout(function () {
if ($.trim($(this).val()) == "") {
$(this).val(swap_val[i]);
}
});
});
2、 Jquery限制输入框内容长度,中文占2个字符长度
$(function() {
$("#txt").bind("keyup change",
function() {
var len = $(this).val();
var total = 0;
var han = 0;
for (i = 0; i < len.length; i++) {
if (len[i].match(/[^\x00-\xff]/ig) != null) {
han++;
}
total = len.length + han;
}
if (total <= 10) {
$("#tip").html(total);
} else {
$("#tip").html("最多10个字符").css({
color: "#f40"
});
}
})
})
3、平滑滚动页面到某个锚点
$(document).ready(function() {
$("a.topLink").click(function() {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top + "px"
}, {
duration: 500,
easing: "swing"
});
return false;
});
});
4、鼠标滑动时的渐入和渐出
$(document).ready(function(){
$(".thumbs img").fadeTo("slow", 0.6); // 这设置的透明度
$(".thumbs img").hover(function(){
$(this).fadeTo("slow", 1.0);
},function(){
$(this).fadeTo("slow", 0.6);
});
});
5、制作等高的列
var max_height = 0;
$("div.col").each(function(){
if ($(this).height() > max_height) { max_height = $(this).height(); }
});
$("div.col").height(max_height);
6、在一些老的浏览器上启用 HTML5 的支持
(function(){
if(!/*@cc_on!@*/0)
return;
var e =
"abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav
,output,progress,section,time,video".split(','),i=e.length;while(i--){document.createElement(e[i])}
})()
//然后在head中引入该js
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
7、测试浏览器是否支持某些 CSS3 属性
var supports = (function() {
var div = document.createElement('div'),
vendors = 'Khtml Ms O Moz Webkit'.split(' '),
len = vendors.length;
return function(prop) {
if ( prop in div.style ) return true;
prop = prop.replace(/^[a-z]/, function(val) {
return val.toUpperCase();
});
while(len--) {
if ( vendors[len] + prop in div.style ) {
// browser supports box-shadow. Do what you need.
// Or use a bang (!) to test if the browser doesn't.
return true;
}
}
return false;
};
})();
if ( supports('textShadow') ) {
document.documentElement.className += ' textShadow';
8、获取 URL 中传递的参数
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return results[1] || 0;
}
9、禁用表单的回车键提交
$("#form").keypress(function(e) {
if (e.which == 13) {
return false;
}
});
10. 使用jQuery来切换样式表
$("link[media='screen']").attr("href", "Alternative.css");
11.jQuery检测浏览器类型
(if( $.browser.safari))
(if ($.browser.msie && $.browser.version > 6 ))
(if ($.browser.msie && $.browser.version <= 6 ))
(if ($.browser.mozilla && $.browser.version >= '1.8' ))
12. jQuery验证某个元素是否为空
if ($("#Demo").html()) { //null;}
13. jQuery从集合中获得索引值
$("ul > li").click(function () {
var index = $(this).prevAll().length;
});
14. jQuery选择被选中的option元素
$("#someElement").find("option:selected");
15. jQuery为选择器绑定方法
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
}); //1.42版后,delegate替代live,因为它们提供了更好的上下文支持
16. jQuery自动滚动到页面中的某区域(可以看做一个小插件)
jQuery.fn.Autoscroll = function(sel) {
$('html,body').animate(
{scrollTop: $(sel).offset().top},500
);
} //调用:$("#area_name").Autoscroll();
17. jQuery限制"TextArea"域中的字符数(可以看做一个小插件)
(function($) {
jQuery.fn.maxLength = function(max){
this.each(function(){
var type = this.tagName.toLowerCase();
var inputType = this.type ? this.type.toLowerCase() : null;
if (type == "input" && inputType == "text" || inputType == "password") {
//应用标准的maxLength
this.maxLength = max;
}
else
if (type == "textarea") {
this.onkeypress = function(e){
var ob = e || event;
var keyCode = ob.keyCode;
var hasSelection = document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart !=
this.selectionEnd;
return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !
ob.ctrlKey && !ob.altKey && !hasSelection);
};
this.onkeyup = function(){
if (this.value.length > max) {
this.value = this.value.substring(0, max);
}
};
}
});
})(jQuery); //调用:$('#macoArea").maxLength(500);
18. jQuery判断某个元素是否可见
if($("#macoArea").is(":visible") == "true") { //少年,别跑 }
19. jQuery元素居中显示(可以看做一个小插件)
(function($) {
jQuery.fn.center = function () {
this.css('position','absolute');
this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollTop() + 'px');
this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');
return this;
}
})(jQuery); //调用:$("#macoArea").center();
20. jQuery使用.siblings()选择同辈元素
// 少年,你是否这样操作过
$('#nav li').click(function(){
$("#macoArea li").removeClass("current");
$(this).addClass("current");
});
//这样做是不是会更好呢
$("#nav li").click(function(){
$(this).addClass("current").siblings().removeClass("current");
});
21. jQuery操作复选框全选反选
var sta = false; //你懂,全局东东
$('a').click(function() {
$("input[type=checkbox]").attr("checked",!sta);
sta = !sta;
});
22. jQuery获得鼠标光标位置x和y
$(document).mousemove(function(e)}
$(document).ready(function() {
$().mousemove(function(e){
$("#macoArea").html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
});
23. jQuery解析XML
function ParseXml(xml) {
$(xml).find("Node").each(function(){
$("#macoArea").append($(this).attr("Author") + "");
);
}
24. jQuery判断图像是否被完全加载进来
$('#demoImg').attr("src", "demo.jpg").load(function() {
alert("是的,你看到的是真的");
});
25. jQuery让Cookie过期
var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie("example", "foo", { expires: date });;
26. jQuery禁止鼠标右键
view source
print?
$(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});
27.jQuery自动根据图片高度宽度缩
jQuery.fn.ImageAutoSize = function(width,height){
$(“img”,this).each(function(){
var image = $(this);
if(image.width()>width){
image.width(width);
image.height(width/image.width()*image.height());
}
if(image.height()>height){
image.height(height);
image.width(height/image.height()*image.width());
}
});
}
调用:先引用上面的脚本或将上页的脚本放入自己的JS库,然后只要再加 $(function(){ $(“图片组所在的容器”).ImageAutoSize(限制最大宽,限
1、如何显示或是删除input域中的默认值
//这段代码展示了在用户未输入值时,
//如何在文本类型的input域中保留
//一个默认值
wap_val = [];
$(".swap").each(function (i) {
wap_val[i] = $(this).val();
$(this).focusin(function () {
if ($(this).val() == swap_val[i]) {
$(this).val("");
}
}).focusout(function () {
if ($.trim($(this).val()) == "") {
$(this).val(swap_val[i]);
}
});
});
2、 Jquery限制输入框内容长度,中文占2个字符长度
$(function() {
$("#txt").bind("keyup change",
function() {
var len = $(this).val();
var total = 0;
var han = 0;
for (i = 0; i < len.length; i++) {
if (len[i].match(/[^\x00-\xff]/ig) != null) {
han++;
}
total = len.length + han;
}
if (total <= 10) {
$("#tip").html(total);
} else {
$("#tip").html("最多10个字符").css({
color: "#f40"
});
}
})
})
3、平滑滚动页面到某个锚点
$(document).ready(function() {
$("a.topLink").click(function() {
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top + "px"
}, {
duration: 500,
easing: "swing"
});
return false;
});
});
4、鼠标滑动时的渐入和渐出
$(document).ready(function(){
$(".thumbs img").fadeTo("slow", 0.6); // 这设置的透明度
$(".thumbs img").hover(function(){
$(this).fadeTo("slow", 1.0);
},function(){
$(this).fadeTo("slow", 0.6);
});
});
5、制作等高的列
var max_height = 0;
$("div.col").each(function(){
if ($(this).height() > max_height) { max_height = $(this).height(); }
});
$("div.col").height(max_height);
6、在一些老的浏览器上启用 HTML5 的支持
(function(){
if(!/*@cc_on!@*/0)
return;
var e =
"abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav
,output,progress,section,time,video".split(','),i=e.length;while(i--){document.createElement(e[i])}
})()
//然后在head中引入该js
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
7、测试浏览器是否支持某些 CSS3 属性
var supports = (function() {
var div = document.createElement('div'),
vendors = 'Khtml Ms O Moz Webkit'.split(' '),
len = vendors.length;
return function(prop) {
if ( prop in div.style ) return true;
prop = prop.replace(/^[a-z]/, function(val) {
return val.toUpperCase();
});
while(len--) {
if ( vendors[len] + prop in div.style ) {
// browser supports box-shadow. Do what you need.
// Or use a bang (!) to test if the browser doesn't.
return true;
}
}
return false;
};
})();
if ( supports('textShadow') ) {
document.documentElement.className += ' textShadow';
8、获取 URL 中传递的参数
$.urlParam = function(name){
var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (!results) { return 0; }
return results[1] || 0;
}
9、禁用表单的回车键提交
$("#form").keypress(function(e) {
if (e.which == 13) {
return false;
}
});
10. 使用jQuery来切换样式表
$("link[media='screen']").attr("href", "Alternative.css");
11.jQuery检测浏览器类型
(if( $.browser.safari))
(if ($.browser.msie && $.browser.version > 6 ))
(if ($.browser.msie && $.browser.version <= 6 ))
(if ($.browser.mozilla && $.browser.version >= '1.8' ))
12. jQuery验证某个元素是否为空
if ($("#Demo").html()) { //null;}
13. jQuery从集合中获得索引值
$("ul > li").click(function () {
var index = $(this).prevAll().length;
});
14. jQuery选择被选中的option元素
$("#someElement").find("option:selected");
15. jQuery为选择器绑定方法
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
}); //1.42版后,delegate替代live,因为它们提供了更好的上下文支持
16. jQuery自动滚动到页面中的某区域(可以看做一个小插件)
jQuery.fn.Autoscroll = function(sel) {
$('html,body').animate(
{scrollTop: $(sel).offset().top},500
);
} //调用:$("#area_name").Autoscroll();
17. jQuery限制"TextArea"域中的字符数(可以看做一个小插件)
(function($) {
jQuery.fn.maxLength = function(max){
this.each(function(){
var type = this.tagName.toLowerCase();
var inputType = this.type ? this.type.toLowerCase() : null;
if (type == "input" && inputType == "text" || inputType == "password") {
//应用标准的maxLength
this.maxLength = max;
}
else
if (type == "textarea") {
this.onkeypress = function(e){
var ob = e || event;
var keyCode = ob.keyCode;
var hasSelection = document.selection ? document.selection.createRange().text.length > 0 : this.selectionStart !=
this.selectionEnd;
return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !
ob.ctrlKey && !ob.altKey && !hasSelection);
};
this.onkeyup = function(){
if (this.value.length > max) {
this.value = this.value.substring(0, max);
}
};
}
});
})(jQuery); //调用:$('#macoArea").maxLength(500);
18. jQuery判断某个元素是否可见
if($("#macoArea").is(":visible") == "true") { //少年,别跑 }
19. jQuery元素居中显示(可以看做一个小插件)
(function($) {
jQuery.fn.center = function () {
this.css('position','absolute');
this.css('top', ( $(window).height() - this.height() ) / +$(window).scrollTop() + 'px');
this.css('left', ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + 'px');
return this;
}
})(jQuery); //调用:$("#macoArea").center();
20. jQuery使用.siblings()选择同辈元素
// 少年,你是否这样操作过
$('#nav li').click(function(){
$("#macoArea li").removeClass("current");
$(this).addClass("current");
});
//这样做是不是会更好呢
$("#nav li").click(function(){
$(this).addClass("current").siblings().removeClass("current");
});
21. jQuery操作复选框全选反选
var sta = false; //你懂,全局东东
$('a').click(function() {
$("input[type=checkbox]").attr("checked",!sta);
sta = !sta;
});
22. jQuery获得鼠标光标位置x和y
$(document).mousemove(function(e)}
$(document).ready(function() {
$().mousemove(function(e){
$("#macoArea").html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
});
});
23. jQuery解析XML
function ParseXml(xml) {
$(xml).find("Node").each(function(){
$("#macoArea").append($(this).attr("Author") + "");
);
}
24. jQuery判断图像是否被完全加载进来
$('#demoImg').attr("src", "demo.jpg").load(function() {
alert("是的,你看到的是真的");
});
25. jQuery让Cookie过期
var date = new Date();
date.setTime(date.getTime() + (x * 60 * 1000));
$.cookie("example", "foo", { expires: date });;
26. jQuery禁止鼠标右键
view source
print?
$(function(){
$(document).bind("contextmenu",function(e){
return false;
});
});
27.jQuery自动根据图片高度宽度缩
jQuery.fn.ImageAutoSize = function(width,height){
$(“img”,this).each(function(){
var image = $(this);
if(image.width()>width){
image.width(width);
image.height(width/image.width()*image.height());
}
if(image.height()>height){
image.height(height);
image.width(height/image.height()*image.width());
}
});
}
调用:先引用上面的脚本或将上页的脚本放入自己的JS库,然后只要再加 $(function(){ $(“图片组所在的容器”).ImageAutoSize(限制最大宽,限
制最大高);});
<script type="text/javascript">
//屏蔽右键菜单
document.oncontextmenu = function (event){
if(window.event){
event = window.event;
}try{
var the = event.srcElement;
if (!((the.tagName == "INPUT" && the.type.toLowerCase() == "text") || the.tagName == "TEXTAREA")){
return false;
}
return true;
}catch (e){
return false;
}
}
</script>