您的位置:首页 > Web前端 > JavaScript

一些实用的JS

2015-01-09 15:30 148 查看
1.str.split(/\s+/)
这句是表示以和/\s+/匹配的字符串作为分界,分割字符串str
比如一个空格或者多个或者空格以及回车等 其中+表示一个或者多个
var a = "b-c-d";
var d = a.split("-");
alert(d[1]); //c

2.var up_class;
if(!(up_class = $(this).data('up_class'))) $(this).data('up_class', up_class = $(this).attr('class').split(/\s+/)[0] + '-up');
其中 if(!undefined) 这个返回的是TRUE;//这边注意了哦

3.以NUll undefined "空" 作为条件 返回的是false;

4.JS将一个数取整 :
1.parseInt(str)
2.Math.ceil(number) //返回大于等于其数值参数的最小整数。
3.Math.floor(number) //返回小于等于其数值参数的最大整数。
4.Math.round(number) //四舍五入

5.parseInt("12abc") // 返回 12。 把一组字符串变成数字

6.Data.parse()
Date.parse方法是Date对象的一个静态方法,其作用是“解析一个包含日期的字符串,并返回该日期与 1970 年 1 月 1 日午夜之间所间隔的毫秒
数”。格式为:  Date.parse(dateVal)   这个方法是很常用的,比如在验证输入日期是否存在时,可以使用它,如果是一个不存在的日期,则其返回值将是NaN,另外如果要比较两个日期的先后,或是计算两个日期相差的天数 ,都可以用到。  今天在使用它比较日期先后的时候遇到了一个奇怪的问题,是关于日期格式的,parse方法要求短日期可以使用“/”或“-”作为分隔符,但是必须用月 /日/年的格式来表示,例如今天是“7/6/2008”或是“7-6-2008”,问题就出现在这里,当使用“7-6-2008”这种格式时,在IE中可以正常解析,但在FireFox中,返回值却总是NaN。一开始以为是代码出现问题,检查以后才发现是浏览器的原因,后来将格式改为“7/6/2008” 后在IE和FF中都可以正常解析了。

7.服务器和客户端时间同步
var ServerDate = new Date(2010,09,27,09,42,46);
var ClientDate= new Date();
var d=ClientDate-ServerDate;//计算S和C之间的时差,单位毫秒
function display()
{
var today=new Date();//以当前时间和日期来创建DATE对象
today.setTime(today.getTime()-d);//同步日期到服务器时间
var year=today.getFullYear();//获取当前年份
var month=today.getMonth();//获取当前月份
var day=today.getDate();//获取当前日期
var week=today.getDay();//获取当前日期对应的星期
var hours=today.getHours();//获取当前小时
var minutes=today.getMinutes();//获取当前分钟
var seconds=today.getSeconds();//获取当前秒钟 }

8. toUpperCase() 将一串小写的字母转换成大写的字母

9.第一次点击和第二次点击不一样
function click_action(){
alert('第一次');
var click_action2 = alertMsg("第二次了!");
document.getElementById("enjoy").onclick = click_action2 ; //不可以.
}
function alertMsg(t) {
return function(){
alert(t);
}
}

10 /*获取对象*/
var $ = function (id){
return document.getElementById(id);
};

11. 阻止浏览默认
function stopBubble(e) {
//如果提供了事件对象,则这是一个非IE浏览器
if ( e && e.stopPropagation )
//因此它支持W3C的stopPropagation()方法
e.stopPropagation();
else
//否则,我们需要使用IE的方式来取消事件冒泡
window.event.cancelBubble = true;
}
//阻止浏览器的默认行为
function stopDefault( e ) {
//阻止默认浏览器动作(W3C)
if ( e && e.preventDefault )
e.preventDefault();
//IE中阻止函数器默认动作的方式
else
window.event.returnValue = false;
return false;
}
使用方法:
//监视用户何时把鼠标移到元素上,
//为该元素添加红色边框
unionDom[i].onmouseover = function(e) {
this.style.border = "1px solid red";
stopBubble( e );
};
//监视用户何时把鼠标移出元素,
//删除我们所添加的红色边框
unionDom[i].onmouseout = function(e) {
this.style.border = "0px";
stopBubble( e );
};

12 x = Math.cos(3 * Math.PI) + Math.sin(Math.LN10); y = Math.tan(14 * Math.E)
如果用math语句的话,可以改写成如下:
with(Math){
x=cos(3*PI)+sin(Math.LN10);
y=tan(14*E);
}
IF(K){k}
IF(K)ELSE{k}

12 input 自动适应宽度
checkLength(cityspan,15,22)
checkLength:function(which,maxchar,fonsize){ //input 输入框自适应宽度 maxchar=最大宽度 fonsize=字体大小
iCount = which.val().length;
if(iCount<=maxchar) which.css({ width: iCount*fonsize+'px'});
}

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
$.ajax({
type: 'GET',
url: "someurl"l,
processData: true,
data: {},
dataType: "json",
success: function (data) { processData(data); }
});

13 jQuery AJAX EX:
获取:
$(function()
{
value = escape("上海");
$.ajax({
url: "http://www.1hai.cn/AsyncData.aspx?action=getbstore1&city=" + value,
type: 'get',
success: function(data)
{
var dataObj = eval("(" + data + ")");
alert(dataObj.storehouses[0].district);
}
});
})
发送:
$(function()
{
var textarea=$('#TextArea1').val();
var contact=$('#Text1').val();
var erroUrl=document.URL;
$.ajax({
type: "POST",
url: 'url',
data: 'textarea='+textarea+'&contact='+contact+'&erroUrl='+erroUrl,//xml
success: function(){
alert("您的意见已经成功提交,非常感谢你的意见.");
tjy.tjyBox.fadeOut("slow");
tjy.bgScreen.fadeOut("slow");
}
});
}

14 获取当前页URL
document.location="url";(只读)
document.location.reload("url";);
window.location="url";
location="url";
document.href="url"
document.location.href="url"
document.location.replace="url"
document.action="url"; document.submit();
document.location.href和document.location.replace都可以实现从A页面切换到B页面,但他们的区别是:
用document.location.href切换后,可以退回到原页面。而用document.location.replace切换后,不可以通过“后退”退回到原页面。
关于document.location.href或其他可回退的切换方式
document.location 相当于 document.URL 声明了装载文档的URL,
除非发生了服务器重定向, 否则该属性的值与Window.location.href的值是一样的.
history.go(-1);//返回上一页
document.IFRAME名称.location.href='url';//改变框架内容

15.弹出层失去焦点隐藏:
var flag = false;
$(".selectbox").hover(function() { flag = true }, function() { flag = false })
$(document).mousedown(function(e)
{
e = window.e || e;
var target = e.target || e.srcElement;
if (!flag && target != $(".selectbox")) { $(".selectbox").hide(); }
})

16.JS获取URL参数
<script type="text/javascript">
function GetUrlParms()
{
var args = new Object();
var query = location.search.substring(1); //获取查询串
var pairs = query.split("&"); //在逗号处断开
for (var i = 0; i < pairs.length; i++)
{
var pos = pairs[i].indexOf('='); //查找name=value
if (pos == -1) continue; //如果没有找到就跳过
var argname = pairs[i].substring(0, pos); //提取name
var value = pairs[i].substring(pos + 1); //提取value
args[argname] = unescape(value); //存为属性
}
return args;
}
var args = new Object();
args = GetUrlParms();
var value = args["c"];

alert(value);

</script>

17.JS的共用

var notice = ['电子邮件', '手机号码', '姓名', '证件号码', '驾照号码', '家庭地址', '紧急联系人姓名', '紧急联系人电话', '紧急联系人地址']
$('.usermain input[type="text"]').each(function(i)
{
$(this).focus(function() { this.select(); $(this).addClass('color333') }).blur(function()
{
if ($(this).val().indexOf('请输入') > -1 || $(this).val() == '')
{
$(this).val('请输入' + notice[i]).removeClass('color333')
}
else $(this).addClass('color333')
})
})

18. 文本框文字提示(可优化)
$(function()
{
/*提示文字处理*/
$(".input-txt").focus(function()
{
if ($(this).attr("value") == $(this).attr("null"))
{
$(this).attr("value", "").addClass("current");
}
})
$(".step1-box .code-box .input-txt").blur(function()
{
if ($(this).attr("value") == "")
{
$(this).attr("value", $(this).attr("null")).removeClass("current");
}
})
})

19.setTimeout延迟传值函数问题:
<script type="text/javascript">
$(function()
{
$(".test-box").click(function()
{
var _obj = $(this);
window.setTimeout(function() { anime(_obj); }, 1000);
})
})

function anime(_obj)
{
_obj.css("background", "red");
}
</script>

20.判断图片加载完成后显示
EX1:_img.load(function(){完成后执行XXX});
EX2:
<script type="text/javascript">
var _imgInterval = setInterval(function()
{
var _completed = 0;
var _img = $(".ul li img");
_img.each(function()
{
if (this.complete)
{
$(this).fadeIn("slow");
_completed++;
}
if (_completed == _img.length)
{
clearInterval(_imgInterval);
}
});
}, 100);
</script>

21.自适应屏幕高宽度全屏
<script type="text/javascript">
(function($)
{
$(function()
{
_mainBox();
$(window).resize(function()
{
_mainBox();
});
function _mainBox()
{
var arrPageSizes = ___getPageSize();
var _winW = arrPageSizes[0];
var _winH = arrPageSizes[1];
if (_winW > 1000)
{
$(".outer").width(_winW);
$(".main").width(_winW - 120);
} else
{
$(".outer").width(1000);
$(".main").width(880);
}
if (_winH > 600)
{
$(".outer").css("height", "100%");
$(".navShadow,.navShadow2,.newsList").css("height", "100%");
} else
{
$(".outer").height(600);
$(".navShadow,.navShadow2,.newsList").height(600);
}
var _mainHalf = $(".main").height() / 2;
/*if(!_mainHalf%2==0){
_mainHalf = _mainHalf+0.5;
}else{
_mainHalf = _mainHalf;
}*/
$(".navC").height(_mainHalf);
}
/*for(i=0;i<2;i++){
var _length = $(".navHover .ul").eq(i).find("li").length;
var _height = 42*_length;
$(".navHover .ul").eq(i).height(_height);
$(".navHover .ul").eq(i).css({"top":"50%","marginTop":-_height/2});
}*/
function ___getPageSize()
{
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY)
{
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight)
{ // all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else
{ // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight)
{ // all except Explorer
if (document.documentElement.clientWidth)
{
windowWidth = document.documentElement.clientWidth;
} else
{
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight)
{ // Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body)
{ // other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if (yScroll < windowHeight)
{
pageHeight = windowHeight;
} else
{
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if (xScroll < windowWidth)
{
pageWidth = xScroll;
} else
{
pageWidth = windowWidth;
}
arrayPageSize = new Array(pageWidth, pageHeight, windowWidth, windowHeight);
return arrayPageSize;
};
});
})(jQuery);
</script>

22.JQ键盘事件(↑、↓、Enter)
<script language="javascript" type="text/javascript">
function ShowSelectItem(divId)
{
$("#hint div").css("background-color", "White");
$("#" + divId).css("background-color", "Gray");
$("#search").val($("#" + divId).text());
}
function SelectItemEvent()
{
var items = $("#hint div");
var selected = 1; //默认选第一个
ShowSelectItem(selected);
//捕捉键盘事件
$(document).keydown(function(e)
{
if (e.keyCode == 38)
{ //按了上箭头
selected--;
if (selected < 1)
{
selected = 5;
}
ShowSelectItem(selected);
}
else if (e.keyCode == 40)
{ //按了下箭头
selected++;
if (selected > 5)
{
selected = 1;
}
ShowSelectItem(selected);
}
else if (e.keyCode == 13)
{
alert(“Enter”);
}
});
}
$(document).ready(function()
{
SelectItemEvent();
});
</script>

23.input获得焦点文本选中光标移动到最后
EX1:
function setFocus() {
var range = this.createTextRange(); //建立文本选区
range.moveStart('character', this.value.length); //选区的起点移到最后去
range.collapse(true);
range.select();
}

$('input').bind('focus',function(){
if($.browser.msie){
setFocus.call(this);
} else{
this.setFocus();
}
});

EX2:
$.fn.extend({
clicktext: function()
{
$(this).click(function()
{
$(this).select();
})
}
})
$('input').clicktext();

24.兼容标准浏览器的focus():
var _id;
$(".input-check").blur(function() {
_id = $(this).attr("id");
$(this).hide().parents(".value").find(".check-error").show();
})
$(".check-error").mousedown(function() {
$(this).hide().parents(".value").find(".input-check").show();
window.setTimeout(function() { jQuery("#" + _id + "").focus(); }, 0);
})

25.导航菜单延迟
var navFun = function() {
var mouseover_tid = [];
var mouseout_tid = [];

$(".header .nav li").each(function(index) {
$(this).hover(
function() {
var _self = this;
clearTimeout(mouseout_tid[index]);
mouseover_tid[index] = setTimeout(function() {
$(_self).addClass("hover").children().children("i, .nav-show").fadeIn(300);
}, 200);
},
function() {
var _self = this;
clearTimeout(mouseover_tid[index]);
mouseout_tid[index] = setTimeout(function() {
$(_self).removeClass("hover").children().children("i, .nav-show").fadeOut(300);
}, 200);
})
})
}
navFun();

26.获取鼠标坐标
EX1:
$('#testDiv').mousemove(function(e) {
var _x = e.originalEvent.x || e.originalEvent.layerX || 0;
var _y = e.originalEvent.y || e.originalEvent.layerY || 0;
$(this).text(_x + '---' + _y);
})

EX2:
function mousePos(e) {
var x, y;
var e = e || window.event;
return {
x: e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft,
y: e.clientY + document.body.scrollTop + document.documentElement.scrollTop
};
};
function test(e) {
document.getElementById("mjs").innerHTML = mousePos(e).x + ',' + mousePos(e).y;
};

EX3:
function mouseMove(e) {
e = e || window.event;
var mousePos = mouseCoords(e);
alert(mousePos.x + "-" + mousePos.y);
}
function mouseCoords(e) {
if (e.pageX || e.pageY) {
return { x: e.pageX, y: e.pageY };
}
return {
x: e.clientX + document.body.scrollLeft - document.body.clientLeft,
y: e.clientY + document.body.scrollTop - document.body.clientTop
};
}
document.onmousemove = mouseMove;

27.拖拽容器(图片BUG处理)
function moveFun() {
var objX, objY, posX, posY, moveX, moveY;
function mousePos(e) {
var x, y;
var e = e || window.event;
return {
x: e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft,
y: e.clientY + document.body.scrollTop + document.documentElement.scrollTop
};
};

$("#lightbox-container-image-box").mousedown(function(e) {
$(this).attr('ismove', 'true');
objX = $(this).parents("#jquery-lightbox").offset().left;
objY = $(this).parents("#jquery-lightbox").offset().top;
posX = mousePos(e).x;
posY = mousePos(e).y;
}).mousemove(function(e) {
if ($.trim($(this).attr('ismove')) == 'false') {
return false;
}
if (e.button != 0 && e.button != 1) {
return false;
}

moveX = mousePos(e).x;
moveY = mousePos(e).y;
var resultX = objX + moveX - posX;
var resultY = objY + moveY - posY;
$("#jquery-lightbox").css({ "top": resultY, "left": resultX });
return false;
}).mouseup(function() {
$(this).attr('ismove', 'false');
});
}

28.jQuery获取Select选择的Text和Value
1. $("#select_id").change(function(){//code...}); //为Select添加事件,当选择其中一项时触发
2. var checkText=$("#select_id").find("option:selected").text(); //获取Select选择的Text
3. var checkValue=$("#select_id").val(); //获取Select选择的Value
4. var checkIndex=$("#select_id ").get(0).selectedIndex; //获取Select选择的索引值
5. var maxIndex=$("#select_id option:last").attr("index"); //获取Select最大的索引值
jQuery添加/删除Select的Option项:
1. $("#select_id").append("<option value='Value'>Text</option>"); //为Select追加一个Option(下拉项)
2. $("#select_id").prepend("<option value='0'>请选择</option>"); //为Select插入一个Option(第一个位置)
3. $("#select_id option:last").remove(); //删除Select中索引值最大Option(最后一个)
4. $("#select_id option[index='0']").remove(); //删除Select中索引值为0的Option(第一个)
5. $("#select_id option[value='3']").remove(); //删除Select中Value='3'的Option
5. $("#select_id option[text='4']").remove(); //删除Select中Text='4'的Option
内容清空:$("#charCity").empty();

29.js对文字进行编码及解码函数
编码:escape,encodeURI,encodeURIComponent
解码:unescape,decodeURI,decodeURIComponent
详细:http://user.qzone.qq.com/355582750/blog/1379397017
ajax URL中文乱码问题:encodeURI(encodeURI(url))(二次转码)

30.正则判断是否为网站链接
/^(https?|ftp):\/\/|(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i

31.JS判断鼠标从什么方向进入一个容器
/article/6948833.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>判断鼠标进入方向</title>
</head>
<body>
<style>
html,body{margin:0;padding:0;}
#wrap{width:300px;height:300px;background:#33aa00;margin:50px;display:inline-block;font-size:50px;text-align:center;line-height:300px;}
</style>
<div id="wrap">
方向反馈
</div>
<script type="text/javascript" src="http://common.cnblogs.com/script/jquery.js"></script>
<script>
$("#wrap").bind("mouseenter mouseleave",
function(e) {
var w = $(this).width();
var h = $(this).height();
var x = (e.pageX - this.offsetLeft - (w / 2)) * (w > h ? (h / w) : 1);
var y = (e.pageY - this.offsetTop - (h / 2)) * (h > w ? (w / h) : 1);
var direction = Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
var eventType = e.type;
var dirName = new Array('上方','右侧','下方','左侧');
if(e.type == 'mouseenter'){
$(this).html(dirName[direction]+'进入');
}else{
$(this).html(dirName[direction]+'离开');
}
});
</script>
</body>
</html>

32.JS模拟监听触屏滑动方向

//模拟触屏事件

var touchFun = function() {
var x_m_d = null;
var x_m_u = null;
var direction = null;
var m_d = false;
var objPos = null;
document.getElementById("banner").addEventListener('touchstart', m_down, false);
document.getElementById("banner").addEventListener('touchmove', m_move, false);
document.getElementById("banner").addEventListener('touchend', m_up, false);

function m_down(e) {
x_m_d = e.touches[0].pageX;
m_d = true;
objPos = $('.tab-banner-content li.current').offset().left;
}

function m_move(e) {
x_m_u = e.touches[0].pageX;
direction = x_m_u - x_m_d;
if (direction > 10 || direction < -10) {
event.preventDefault();
}
clearInterval(timeoutSet);
if (m_d) {
$('.tab-banner-content li.current').css('left', objPos + direction);
}
}

function m_up(e) {
if (m_d) {
if (direction > 50) {
prevFun();
} else {
$('.tab-banner-content li.current').stop().animate({
'left': objPos
}, 'slow');
}
if (direction < -50) {
nextFun();
}
}
timeoutSet = setInterval(nextFun, timeoutTime);
}
}
touchFun();

33.JS屏蔽链接拖动后打开新窗口

$('a').on('mouseup mousedown mouseout', function(e) {
if (e && e.preventDefault) {
e.preventDefault();
} else {
window.event.returnValue = false;
}
});
$('a').on('click', function(e) {
window.location.href = this.href;
});

34.HTML 5 全局 contenteditable 属性,容器内容可编辑模式
<p contenteditable="true">这是一段可编辑的段落。请试着编辑该文本。</p>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: