在线代码编辑器 CODEMIRROR 配置说明
CodeMirror是一款在线的支持语法高亮的代码编辑器。官网: http://codemirror.net/
下载后,解压开得到的文件夹中,lib下是放的是核心库和核心css,mode下放的是各种支持语言的语法定义,theme目录下是支持的主题样式。一般在开发中,添加lib下的引用和mode下的引用就够了。
全局事件ajaxStart、ajaxStop不执行
最近一直都在研究【锋利的jQuery】,确实是一本好书,受益匪浅。但由于技术发展及版本更新等原因,里面还是有些坑需要踩的。
比如:第六章七节中提到的全局事件ajaxStart、ajaxStop照着案例敲结果并不会执行。
在查阅资料后,发现原来在jquery1.9+版本以后,ajax全局事件需绑定到document对象上才能触发。
下面是各版本不同写法: 阅读详细 »
页面滚动到底部 ajax加载内容代码 示例代码
页面滚动到底部 ajax加载内容代码:
html结构:
<div class="ipshowListA">
<ul class="clearfix">
<!--<li class="item">内容块</li>-->
</ul>
</div>
<div class="pagesA">
<div class="more" data-url = "jsonlist.php?page=1" >点击加载更多</div>
<div class="loading"><!--数据加载中...--></div>
<div class="nodata">没有更多数据了...</div>
</div>
js代码:
// JavaScript Document
$(function(){
var $btn_more = $('.pagesA .more');//更多按钮
var $btn_loading = $('.pagesA .loading');//载入中
var $btn_nodata = $('.pagesA .nodata');//没有数据了
var $box = $('.ipshowListA ul');//容器
var lock = false;
var nexturl = $btn_more.data('url');//第一次url
function _more(){
$btn_more.show();
$btn_loading.hide();
$btn_nodata.hide();
}
function _loading(){
$btn_more.hide();
$btn_loading.show();
$btn_nodata.hide();
}
function _nodata(){
$btn_more.hide();
$btn_loading.hide();
$btn_nodata.show();
}
//点击触发 (ajax加载数据)
$btn_more.on('click',function(){
ajaxLoad();
});
//距离底部300触发 (ajax加载数据)
$(window).on('scroll',function(){
if( $(document).height() - $(window).scrollTop() - $(window).height() < 300 ){
ajaxLoad();
}
})
//ajax加载数据
function ajaxLoad(){
//锁
if( lock ){return false; }else{ lock = true; }
_loading();
$.ajax({
url:nexturl,
type:'get',
dataType:'json',
success:function(d){
//{"error":0 , "msg":"ok" , "html":"6666", "nexturl":"jsonlist.php?page=1"}
if(d.error == 0 ){
//加载成功
$box.append( d.html );
lock = false;
_more();
nexturl = d.nexturl; //更新下一页地址
}else if(d.error == 1 ){
//没有数据了
_nodata();
}else{
//其他错误
alert( d.msg );
lock = false;
}
},
error:function( a,b,c){
console.log('ajax错误:', a,b,c );
}
})
}
});
php代码:
<?php
sleep(3);//模拟网络延时 3秒
//返回的 json数据结构
//{"error":0 , "msg":"ok" , "html":"6666", "nexturl":"jsonlist.php?page=1"}
$page = $_GET['page'];
if( $page > 5 ){
//没有数据了
//{"error":1 , "msg":"没有数据了" , "html":"", "nexturl":""}
$j = array();
$j['error'] = 1;
$j['msg'] = '没有数据了';
$j['nexturl'] = '';
$j['html'] = '';
die( json_encode($j) );
}
/////////////////////////////////////////////////////////////////////////////
$page++;
$j = array();
$j['error'] = 0;
$j['msg'] = 'ok';
$j['nexturl'] = 'jsonlist.php?page=' . $page;
$j['html'] = '
<li class="item">内容块</li>
<li class="item">内容块</li>
<li class="item">内容块</li>
...
';
die( json_encode($j) );
jQuery笔记_选择器
2.2.判断dom是否为空 js 直接判断 jQuery if( $('#id').length )
if( $('#id').length > 0 )
if( $('#id')[0] )
if( $('#id').get(0) )
2.3.选择器
2.3.1 基础选择器
#id
.class
h1
*
选择器1 ,选择器2 ,选择器3
2.3.2 层次选择器(关系)
空格
>
+ next()
~ nextAll()
2.3.3 过滤选择器
1.基本的过滤选择器
:first
:last
:not('选择器')
:even 偶数
:odd 奇数
:eq(数) 第几个 index 从0
:gt(数) 大于index的 对象
:lt(数) 大于index的 对象
:header 标题 h1 . h2 , h3 ...
:animated ****正在执行动画的*****
:focus 获取焦点的(表单元素)
2.内容过滤选择器
:contains(text) 选取含有内容 = “text” 的元素
:empty 空元素
:has( selector ) 有 (。。。。)的元素
:parent 与empty相反 选取有内容 或 子元素
3.可见性 过滤选择器
:hidden 不可见 隐藏域<input type="hidden"/> display:none visibility:hidden
:visible 可见
4.属性的过滤选择器
[属性]
[属性=值]
!= 属性的值 不等于 XXX
^= 属性的值 以 xxx 开始
$= 属性的值 以 xxx 结束
*= 属性的值 包含 xxx
|= 属性的值 等于 xxx 或者 以xxx为前缀的
~= 选择属性的值
[属性][属性][属性N] 满足多个属性条件的
5.子元素 过滤选择器
:nth-child( index / even / odd/ 表达式 )
:nth-child(1) 选取每个父元素下的 索引=1的 与:eq(1) 不同
:nth-child(even) :even 偶数
:nth-child(odd) :odd 奇数
:nth-child(2n) 2的倍数 :even 偶数
:nth-child(3n) 3的倍数 :nth-child(3n + 0)
:nth-child(3n+1) 3的倍数 +1
:nth-child(3n-1) 3的倍数 -1
:first-child 选取的是每一个父元素下的 第一个子元素 与 :first 区别
:last-child 选取的是每一个父元素下的 最后一个子元素 与 :last 区别
:only-child 选取的是每一个父元素下的 唯一 一个子元素
6.表单对象属性 过滤选择器
:disabled 选择禁用 <input disabled />
:enabled 可以使用 表单元素 没有 disabled 属性
:checked 被选中的(单选和多选 )
:selected 被选中项 (下拉菜单) $("select option:selected")
2.3.4 表单选择器
:input 选取 input textarea select button( 表单元素 )
:text 选取 单行文本输入框 <input type="text" />
:password 选取 密码输入框 <input type="password" />
:radio 选取 单选按钮 <input type="radio" />
:checkbox 选取 多选按钮 <input type="checkbox" />
:submit 选取 提交按钮 <input type="submit" /> <button type="submit"></button>
:reset 选取 重置按钮 <input type="reset" /> <button type="reset"></button>
:button 选取 重置按钮 <input type="button" /> <button type="button"></button>
:file 选取 上传域 <input type="file" />
input:hidden 选取 隐藏域 <input type="hidden" />
2.5 选择中的注意事项
1.选择器中含有 特殊字符 . # () []
在写 jQuery选择器的时候 加 \\
例如:
<div class="name.aaa#bbb(ccc)ddd[eeee]"></div>
$('.name\\.aaa\\#bbb\\(ccc\\)ddd\\[eeee\\]')
2.属性选择器@符号问题 (历史问题)
3.选择是否有空格问题。
$('.aaa .bbb')
$('.aaa.bbb')
return false ; 可以阻止 a链接 和 提交按钮的 默认动作
用js方法限制文字个数,文字溢出省略号。自己写了一个限制容器文字长度的jQuery插件。
用js方法限制文字个数,文字溢出省略号。自己写了一个限制容器文字长度的jQuery插件。
自己写了一个限制容器文字长度的jQuery插件,用起来还是很方便的。
/**
* $.txtCur();
* @charset utf-8
* @extends jquery.1.8.3
* @example
* $('.info').txtCur({n:50});
* $('.info').txtCur({n:50,z:'...',isTitle:1});
*/
(function($) {
$.fn.extend({
txtCur: function(options) {
//默认参数
var defaults = {
/**截取长度 */
n: 60,
/*结尾添加字符*/
z: '...',
/*是否在标签上 添加 title 属性*/
isTitle: true
}
var options = $.extend(defaults, options);
return this.each(function() {
var o = options;
var $this = $(this);
var s = $this.text(),
s = $.trim(s); //去掉收尾空格
l = s.length,
n = o.n; //设置字符长度为18个
if (l > n) {
//文本所有内容用a标签的title属性提示文本全部内容
if (o.isTitle) {
$(this).attr("title", s);
}
s = $this.text(s.substring(0, n) + o.z);
}
/**/
});
}
});
})(jQuery);
//调用方法
<span txtCur="10">我是文字我是文字我是文字我是文字我是文字</span>
<script type="text/javascript">
$(function() {
$('[txtCur]').each(function() {
var $that = $(this);
var maxNum = $that.attr('txtCur');
$that.txtCur({
n: maxNum
});
})
})
</script>
解决微信及360浏览器无法读取本地图片问题【js base64 图片压缩】
解决微信及360浏览器无法读取本地图片问题【js base64 图片压缩】
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<title>图片压缩</title>
<style>
body { margin:0; padding:0; }
html { font-size:62.5%; }
.imgzip { padding:1em; }
.imgzip .itm { padding-bottom:1em; word-break:break-all; font-size:1.2rem; line-height:1.5em; }
.imgzip .itm .tit { margin-bottom:.5em; background-color:#e71446; color:#FFF; padding:.5rem 1rem; border-radius:3px; }
.imgzip .itm .cnt { padding:1rem; }
.imgzip .itm .cnt img { display:block; max-width:100%; }
.imgzip textarea { width:100%; height:20em; }
</style>
</head>
<body>
<input type="file" accept="image/*;capture=camera" class="input">
<div class="imgzip"></div>
<script>
document.addEventListener('DOMContentLoaded', init, false);
function init() {
var u = new UploadPic();
u.init({
input: document.querySelector('.input'),
callback: function (base64) {
var html = '';
html = '<div class="itm"><div class="tit">图片名称:</div><div class="cnt">' + this.fileName + '</div></div>'
+ '<div class="itm"><div class="tit">原始大小:</div><div class="cnt">' + (this.fileSize / 1024).toFixed(2) + 'KB<\/div><\/div>'
+ '<div class="itm"><div class="tit">编码大小:</div><div class="cnt">' + (base64.length / 1024).toFixed(2) + 'KB<\/div><\/div>'
+ '<div class="itm"><div class="tit">原始尺寸:</div><div class="cnt">' + this.tw + 'px * ' + this.th + 'px<\/div><\/div>'
+ '<div class="itm"><div class="tit">编码尺寸:</div><div class="cnt">' + this.sw + 'px * ' + this.sh + 'px<\/div><\/div>'
+ '<div class="itm"><div class="tit">图片预览:</div><div class="cnt"><img src="' + base64 + '"><\/div><\/div>'
+ '<div class="itm"><div class="tit">Base64编码:</div><div class="cnt"><textarea>' + base64 + '<\/textarea><\/div><\/div>';
document.querySelector('.imgzip').innerHTML = html;
},
loading: function () {
document.querySelector('.imgzip').innerHTML = '读取中,请稍候...';
}
});
}
function UploadPic() {
this.sw = 0;
this.sh = 0;
this.tw = 0;
this.th = 0;
this.scale = 0;
this.maxWidth = 0;
this.maxHeight = 0;
this.maxSize = 0;
this.fileSize = 0;
this.fileDate = null;
this.fileType = '';
this.fileName = '';
this.input = null;
this.canvas = null;
this.mime = {};
this.type = '';
this.callback = function () {};
this.loading = function () {};
}
UploadPic.prototype.init = function (options) {
this.maxWidth = options.maxWidth || 800;
this.maxHeight = options.maxHeight || 600;
this.maxSize = options.maxSize || 3 * 1024 * 1024;
this.input = options.input;
this.mime = {'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'bmp': 'image/bmp'};
this.callback = options.callback || function () {};
this.loading = options.loading || function () {};
this._addEvent();
};
/**
* @description 绑定事件
* @param {Object} elm 元素
* @param {Function} fn 绑定函数
*/
UploadPic.prototype._addEvent = function () {
var _this = this;
function tmpSelectFile(ev) {
_this._handelSelectFile(ev);
}
this.input.addEventListener('change', tmpSelectFile, false);
};
/**
* @description 绑定事件
* @param {Object} elm 元素
* @param {Function} fn 绑定函数
*/
UploadPic.prototype._handelSelectFile = function (ev) {
var file = ev.target.files[0];
this.type = file.type
// 如果没有文件类型,则通过后缀名判断(解决微信及360浏览器无法获取图片类型问题)
if (!this.type) {
this.type = this.mime[file.name.match(/\.([^\.]+)$/i)[1]];
}
if (!/image.(png|jpg|jpeg|bmp)/.test(this.type)) {
alert('选择的文件类型不是图片');
return;
}
if (file.size > this.maxSize) {
alert('选择文件大于' + this.maxSize / 1024 / 1024 + 'M,请重新选择');
return;
}
this.fileName = file.name;
this.fileSize = file.size;
this.fileType = this.type;
this.fileDate = file.lastModifiedDate;
this._readImage(file);
};
/**
* @description 读取图片文件
* @param {Object} image 图片文件
*/
UploadPic.prototype._readImage = function (file) {
var _this = this;
function tmpCreateImage(uri) {
_this._createImage(uri);
}
this.loading();
this._getURI(file, tmpCreateImage);
};
/**
* @description 通过文件获得URI
* @param {Object} file 文件
* @param {Function} callback 回调函数,返回文件对应URI
* return {Bool} 返回false
*/
UploadPic.prototype._getURI = function (file, callback) {
var reader = new FileReader();
var _this = this;
function tmpLoad() {
// 头不带图片格式,需填写格式
var re = /^data:base64,/;
var ret = this.result + '';
if (re.test(ret)) ret = ret.replace(re, 'data:' + _this.mime[_this.fileType] + ';base64,');
callback && callback(ret);
}
reader.onload = tmpLoad;
reader.readAsDataURL(file);
return false;
};
/**
* @description 创建图片
* @param {Object} image 图片文件
*/
UploadPic.prototype._createImage = function (uri) {
var img = new Image();
var _this = this;
function tmpLoad() {
_this._drawImage(this);
}
img.onload = tmpLoad;
img.src = uri;
};
/**
* @description 创建Canvas将图片画至其中,并获得压缩后的文件
* @param {Object} img 图片文件
* @param {Number} width 图片最大宽度
* @param {Number} height 图片最大高度
* @param {Function} callback 回调函数,参数为图片base64编码
* return {Object} 返回压缩后的图片
*/
UploadPic.prototype._drawImage = function (img, callback) {
this.sw = img.width;
this.sh = img.height;
this.tw = img.width;
this.th = img.height;
this.scale = (this.tw / this.th).toFixed(2);
if (this.sw > this.maxWidth) {
this.sw = this.maxWidth;
this.sh = Math.round(this.sw / this.scale);
}
if (this.sh > this.maxHeight) {
this.sh = this.maxHeight;
this.sw = Math.round(this.sh * this.scale);
}
this.canvas = document.createElement('canvas');
var ctx = this.canvas.getContext('2d');
this.canvas.width = this.sw;
this.canvas.height = this.sh;
ctx.drawImage(img, 0, 0, img.width, img.height, 0, 0, this.sw, this.sh);
this.callback(this.canvas.toDataURL(this.type));
ctx.clearRect(0, 0, this.tw, this.th);
this.canvas.width = 0;
this.canvas.height = 0;
this.canvas = null;
};
</script>
</body>
</html>
Lightbox图片弹出层插件效果下载
Lightbox图片弹出层插件效果下载
在线演示地址:http://demo.lrxin.com/2015/09/jquery-lightbox/
下载地址:jquery-lightbox.zip http://pan.baidu.com/s/1jGldIce
jQuery Lazy Load 图片延迟加载 插件 1.7.2
jQuery Lazy Load 图片延迟加载 插件 1.7.2
基于 jQuery 的图片延迟加载插件,在用户滚动页面到图片之后才进行加载。
对于有较多的图片的网页,使用图片延迟加载,能有效的提高页面加载速度。
版本:
·jQuery v1.4.4+
·jQuery Lazy Load v1.7.2
注意事项:
·需要真正实现图片延迟加载,必须将真实图片地址写在 data-original 属性中。若 src 与 data-original 相同,则只是一个特效而已,并不达到延迟加载的功能。
查看demo:http://demo.lrxin.com/2015/09/jquery.lazyload_v1.7.2_demo/
官方地址:http://www.appelsiini.net/projects/lazyload
下载地址:https://github.com/tuupola/jquery_lazyload/
下载地址2: http://pan.baidu.com/s/1o6j9DQ6
demo下载:http://pan.baidu.com/s/1i3ixY6L
js文件下载地址:http://demo.lrxin.com/2015/09/jquery.lazyload_v1.7.2_demo/jquery.lazyload.min.js
示例代码:
<!DOCTYPE html >
<html>
<head>
<meta charset="utf-8" />
<title>jQuery Lazy Load 图片延迟加载1.7.2</title>
<script src="jquery.js"></script>
<script src="jquery.lazyload.min.js"></script>
<script>
$(function(){
$('.lazy img').lazyload({
effect: 'fadeIn'
});
});
</script>
</head>
<body>
<!--
将真实图片地址写在 data-original 属性中,而 src 属性中的图片换成占位符的图片(例如 1x1 像素的灰色图片或者 loading 的 gif 图片)
添加 class="lazy" 用于区别哪些图片需要延时加载,当然你也可以换成别的关键词,修改的同时记得修改调用时的 jQuery 选择器
添加 width 和 height 属性有助于在图片未加载时占满所需要的空间
-->
<div class="lazy" style="width:800px;">
<img src="img/grey.gif" data-original="img/bmw_m1_hood.jpg" width="765" height="574" alt="BMW M1 Hood">
<img src="img/grey.gif" data-original="img/bmw_m1_side.jpg" width="765" height="574" alt="BMW M1 Side">
<img src="img/grey.gif" data-original="img/viper_1.jpg" width="765" height="574" alt="Viper 1">
<img src="img/grey.gif" data-original="img/viper_corner.jpg" width="765" height="574" alt="Viper Corner">
<img src="img/grey.gif" data-original="img/bmw_m3_gt.jpg" width="765" height="574" alt="BMW M3 GT">
<img src="img/grey.gif" data-original="img/corvette_pitstop.jpg" width="765" height="574" alt="Corvette Pitstop">
</div>
</body>
</html>
参数说明:
<script>
$(function(){
$('img.lazy').lazyload({
effect:'fadeIn' , //加载使用的动画效果,如 show, fadeIn, slideDown 等 jQuery 自带的效果,或者自定义动画。Fadein 淡入动画效果 | show 直接显示
effectspeed : 800 , //动画时间。作为 effect 的参数使用:effect(effectspeed) 动画的时间为400毫秒.
event:'scroll' , //绑定事件 scroll click mouseover
threshold : 0, //灵敏度。默认为 0 表示当图片出现在显示区域中的立即加载显示;设为整数表示图片距离 x 像素进入显示区域时进行加载;设为负数表示图片进入显示区域 x 像素时进行加载。 距离 多少像素时, 开始加载
failure_limit : 0, // 容差范围。页面滚动时,Lazy Load 会遍历延迟加载的图片,检查是否在显示区域内,默认找到第 1 张不可见的图片时,就终止遍历。因为 Lazy Load 认为图片的排序是与 HTML 中的代码中的排序相同,但是也可能会出现例外,通过该值来扩大容差范围。 当Lazy Load 在找到第一个未显示的 <img> 标签时,查找已经被终止了, 并没有继续往下遍历. | failure_limit : 10 这样 Lazy Load 会查找到第10个未显示的<img>标签处.当在图片多且布局复杂的页面时, failure_limit 的作用就很大了.
data_attribute : "original", //
skip_invisible : true, //skip_invisible 加载不可见的图片. Lazy Load 插件默认对隐藏的图片不加载(例如 display:none ). 这样做有助于性能的优化.如果希望连隐藏的图片一起加载,则可以把 skip_invisible 设为 false .
data_attribute : 'original' , //真实图片地址的 data 属性后缀
container: $('#container') , //父容器。延迟加载父容器中的图片. 默认 window 当要延迟加载的图片全摆在一个容器中.只需把 container 属性指向摆放 img 的容器的对象.
appear : null, // 图片加载时的事件 (Function),有 2 个参数:elements_left(未加载的图片数量)、settings(lazyload 的参数)
load : null // 图片加载后的事件 (Function),有 2 个参数,同 appear
});
});
</script>
关于 apper 和 load 两个函数的 参数 可以参考下面代码调试
<script>
$(function(){
$('img').lazyload({
effect:'fadeIn'
/*
,
appear:function(elements_left, settings) {
console.log('appear');
console.log(elements_left);
//console.log(this, elements_left, settings);
},
load:function(elements_left, settings) {
console.log('load');
console.log(elements_left);
//console.log(this, elements_left, settings);
}
*/
});
});
</script>
Load Images Using Timeout 定时加载图像
当前显示区域内的图像会进行加载,显示区域以外的图像会在延迟 5 秒之后进行加载。
<script src="/js/jquery-1.7.2.min.js"></script>
<script src="js/jquery.lazyload.min.js"></script>
<script>
$(function(){
$('img').lazyload({
effect:'fadeIn',
event:'sporty'
});
});
$(window).bind('load', function(){
var timeout = setTimeout(function(){
$('img').trigger('sporty')
}, 5000);
});
</script>
Noscript Fallback 不支持 JavaScript 时的降级示例
演示在不支持 JavaScript 的浏览器访问时,是如何运作的。参照下面的代码:
<style>
.lazy {
display: none;
}
</style>
<img class="lazy" src="grey.gif" data-original="example.jpg" width="765" height="574">
<noscript><img src="example.jpg" width="765" height="574"></noscript>
$('img.lazy').show().lazyload({
effect: 'fadeIn'
});
.Page With Gazillion Images 大量图片的示例
当页面中存在上百张,甚至数百张图片时,建议使用 scrollstop 事件。
<script src="jquery.scrollstop.js"></script>
<img src="grey.gif" data-original="example.jpg">
$('img').lazyload({
event: 'scrollstop'
});
自定义 滚动停止事件 scrollstop
jquery.scrollstop.js文件下载地址 : http://demo.lrxin.com/2015/09/jquery.lazyload_v1.7.2_demo/jquery.scrollstop.js
DD_belatedPNG完美解决ie6下png图片半透明问题,支持背景平铺,定位等属性
解决png在ie6下半透明的方法有很多,这里之所以推荐 DD_belatedPNG 是因为 DD_belatedPNG 可以完美的支持
背景平铺 :background-repeat:(no-repeat ,repeat-x,repeat-y ,repeat)
背景定位:background-position:60px 80px;
背景固定:background-attachment:fixed;
等属性。
还支持:鼠标经过效果 a:hover{}
官方网站:http://www.dillerdesign.com/experiment/DD_roundies/
官方引用地址:
0.0.8a.js (官方未压缩版本, ~12Kb) : http://www.dillerdesign.com/experiment/DD_belatedPNG/DD_belatedPNG_0.0.8a.js
0.0.8a-min.js (官方压缩版, ~7Kb) : http://www.dillerdesign.com/experiment/DD_belatedPNG/DD_belatedPNG_0.0.8a-min.js
———————————-
使用方法 :
<!--[if IE 6]>
<script type="text/javascript" src="DD_belatedPNG.js" ></script>
<script type="text/javascript"> DD_belatedPNG.fix('.trans,.box , a:hover, .png_bg'); </script>
<![endif]-->
引用函数是 DD_belatedPNG.fix() , 括号里分别填写应用 PNG-24 的 CSS 选择器(可使用ID选择器和类选择器)和应用类型(分为 img 标签和 background 属性两种)。
如
<script type="text/javascript">
DD_belatedPNG.fix('#box, img');
</script>
或者
<script type="text/javascript">
DD_belatedPNG.fix('.header, background');
</script>
等,这些可以简写成
<script type="text/javascript">
DD_belatedPNG.fix('#box-one, .header, img, background');
</script>
在或者像本例子中直接使用 * 号,表示应用所有 css 选择器及 xhtml 标签。
<script type="text/javascript">
DD_belatedPNG.fix('*');
</script>
DD_belatedPNG.rar:百度网盘http://pan.baidu.com/s/1dDwKBXv
jquery事件绑定只点击一次
jquery事件绑定只点击一次,想法就是绑定事件,函数内在执行时候 取消绑定事件。
$('#my-selector').bind('click', function() {
$(this).unbind('click');
alert('Clicked and unbound!');
});
或者one() 方法为被选元素附加一个或多个事件处理程序,并规定当事件发生时运行的函数。
当使用 one() 方法时,每个元素只能运行一次事件处理器函数。
$("p").one("click",function(){
$(this).animate({fontSize:"+=6px"});
});
jQuery on() 的使用方法
jQuery on()方法是官方推荐的绑定事件的一个方法。
$(selector).on(event,childSelector,data,function,map)
由此扩展开来的几个以前常见的方法有.
bind()
$("p").bind("click",function(){
alert("The paragraph was clicked.");
});
$("p").on("click",function(){
alert("The paragraph was clicked.");
});
delegate()
$("#div1").on("click","p",function(){
$(this).css("background-color","pink");
});
$("#div2").delegate("p","click",function(){
$(this).css("background-color","pink");
});
live()
$("#div1").on("click",function(){
$(this).css("background-color","pink");
});
$("#div2").live("click",function(){
$(this).css("background-color","pink");
});
以上三种方法在jQuery1.8之后都不推荐使用,官方在1.9时已经取消使用live()方法了,所以建议都使用on()方法。
tip:如果你需要移除on()所绑定的方法,可以使用off()方法处理。
$(document).ready(function(){
$("p").on("click",function(){
$(this).css("background-color","pink");
});
$("button").click(function(){
$("p").off("click");
});
});
tip:如果你的事件只需要一次的操作,可以使用one()这个方法
$(document).ready(function(){
$("p").one("click",function(){
$(this).animate({fontSize:"+=6px"});
});
});
trigger()绑定
$(selector).trigger(event,eventObj,param1,param2,...)
$(document).ready(function(){
$("input").select(function(){
$("input").after(" Text marked!");
});
$("button").click(function(){
$("input").trigger("select");
});
});
多个事件绑定同一个函数
$(document).ready(function(){
$("p").on("mouseover mouseout",function(){
$("p").toggleClass("intro");
});
});
多个事件绑定不同函数
$(document).ready(function(){
$("p").on({
mouseover:function(){$("body").css("background-color","lightgray");},
mouseout:function(){$("body").css("background-color","lightblue");},
click:function(){$("body").css("background-color","yellow");}
});
});
绑定自定义事件
$(document).ready(function(){
$("p").on("myOwnEvent", function(event, showName){
$(this).text(showName + "! What a beautiful name!").show();
});
$("button").click(function(){
$("p").trigger("myOwnEvent",["Anja"]);
});
});
传递数据到函数
function handlerName(event)
{
alert(event.data.msg);
}
$(document).ready(function(){
$("p").on("click", {msg: "You just clicked me!"}, handlerName)
});
适用于未创建的元素
$(document).ready(function(){
$("div").on("click","p",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("<p>This is a new paragraph.</p>").insertAfter("button");
});
});
jquery字符输入个数限制插件,支持显示剩余字符个数 iptMaxNum
jquery字符输入个数限制插件,支持显示剩余字符个数 iptMaxNum
———————————
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery限制输入字数</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
/**
* $.iptMaxNum();
* @charset utf-8
* @extends jquery.1.8.3
* @example
* $('#Comment_txt').iptMaxNum({max:50 });
* $('#Comment_txt').iptMaxNum({max:50 , box:"#Comment_txt_num"});
*/
;(function($){
$.fn.extend({
iptMaxNum: function(options) {
//默认参数
var defaults = {
/* 最多多少个字符 */
max:60,
/* 显示个数的容器 选择器*/
box:''
}
var options = $.extend(defaults, options);
return this.each(function(){
var o = options;
var $this = $(this);
var _boxnum =function(){
$(o.box).text( o.max -0 - $this.val().length );
}
_boxnum();
$this.on("keyup , change ",function(){
var curLength=$this.val().length;
if(curLength >= o.max){
var str=$this.val().substring(0, o.max );
$this.val(str);
alert("超过字数限制,多出的字将被截断!" );
}
else{
}
_boxnum();
})
});
}
});
})(jQuery);
</script>
</head>
<body>
您还可以输入<span id="textCount">5</span>个字符<br />
<textarea name="textarea" id="TextArea" cols="45" rows="5" ></textarea>
<script type="text/javascript">
$(function(){
$('#TextArea').iptMaxNum({max:50 , box:"#textCount"});
});
</script>
</body>
</html>
Jquery将Form表单序列化为JSON对象 Serialize Form to JSON
Jquery将Form表单序列化为JSON对象
$("form").serializeObject();
类似
$("form").serialize();
$("form").serializeArray();
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
来源:https://css-tricks.com/snippets/jquery/serialize-form-to-json/
其他方法:
http://blog.csdn.net/flashdelover/article/details/8185775
http://marsvaadin.iteye.com/blog/1717188
Jquery实现如何关闭离开页面时提醒:beforeunload
离开页面提示多般是放到了发新闻或写日志的页面,我们在百度空间或QQ空间在我们未保存信息时如果离开页面都有提示了,下面我来介绍利用jquery的beforeunload来实现此方法。
jquery离开页面弹出提示代码:
//绑定beforeunload事件
$(window).bind('beforeunload',function(){
return '您输入的内容尚未保存,确定离开此页面吗?';
});
//解除绑定,一般放在提交触发事件中
$(window).unbind('beforeunload');
一个简单的,轻量级的JQuery插件用来处理浏览器cookie-jquery.cookie.1.4.1.js
一个简单的,轻量级的JQuery插件用来处理浏览器cookie
jquery.cookie.1.4.1 相对与 jquery.cookie.1.3.x 增加了 许多方法
安装
先包括脚本jQuery库后在引用 jquery.cookie.js 文件:
<script src="/path/to/jquery.cookie.js"></script>
用法
创建cookie:
$.cookie('name', 'value');
创建到期的cookie,有效期7天:
$.cookie('name', 'value', { expires: 7 });
创建到期的cookie,有效期7天,有效范围整个网站:
$.cookie(‘name’, ‘value’, { expires: 7, path: ‘/’ });
$.cookie('name', 'value', { expires: 7, path: '/' });
读取Cookie:
$.cookie('name'); // => "value"
$.cookie('nothing'); // => undefined 不存在的值
读取所有可用的cookie:返回json对象
$.cookie(); // => { "name": "value" }
删除Cookie:
//当Cookie被成功删除,则返回true,否则为false
$.removeCookie('name'); // => true
$.removeCookie('nothing'); // => false
$.cookie('name',null);//v1.3中的老方法
//需要使用相同的属性(路径,域),为什么该cookie用写( 删除cookie 需要相同的 作用范围: 路径 域名 )
$.cookie('name', 'value', { path: '/' });
//这是行不通的!错误方法!
$.removeCookie('name'); // => false
//这将工作!正确方法!
$.removeCookie('name', { path: '/' }); // => true
注意:在删除一个cookie时,必须传递被用来设置Cookie,除非你靠着这是默认选项完全相同的路径,域和安全选项。
———————————
组态
raw
默认情况下,cookie值进行编码/写入/读取时,使用encodeURIComponent / decodeURIComponent解码。绕过此设置原料为true:
$.cookie.raw = true;
JSON
打开作为cookie的值传递JSON对象的自动存储。假设JSON.stringify和JSON.parse:
$.cookie.json = true;
————————–
cookie的选项
cookie的属性可以在全球范围通过设置$ .cookie.defaults对象的属性或单独为通过使一个普通目的是选项的参数每次调用$ .cookie()来设置。每看涨期权覆盖默认选项。
到期(单位:天)
expires: 365
定义cookie的生命周期。值可以是将被解释为天从创建或Date对象的时间数。如果省略,cookie变成一个会话cookie。
路径
path: '/'
定义在哪里cookie有效路径。默认情况下,cookie的路径是cookie的创建页面(标准浏览器的行为)的路径。如果你想使其可用于例如在整个域中使用路径:’/’。默认值:在创建cookie的网页的路径。
——————————————–
注意有关Internet Explorer中:
由于底层的WinINET InternetGetCookie实现一个不起眼的错误,如果与含有一个文件名的路径属性设置IE的的document.cookie不会返回的cookie。
(在Internet Explorer中的Cookie内幕(FAQ))
这意味着使用路径中的一个不能设置的路径:window.location.pathname在情况下,这种路径名包含像文件名,以便:/check.html(或至少,例如饼干不能正确地读出)。
域
domain: 'example.com'
定义在哪里cookie有效的域。默认值:在创建cookie的网页的域名。
安全
secure: true
如果为true,cookie的传输需要一个安全协议(HTTPS)。默认值:false。
转换器
提供一个转换函数作为任选最后一个参数进行读取,以cookie的值更改为在飞行一个不同的表示。
实例解析值成数:
$.cookie('foo', '42');
$.cookie('foo', Number); // => 42
与已经使用转义(第三方Cookie)进行编码处理的cookie:
$.cookie.raw = true;
$.cookie('foo', unescape);
您可以通过任意转换功能。
官方地址:https://github.com/carhartl/jquery-cookie
备用下载:jquery-cookie-v1.4.1
一个jquery写的 导航条,横线跟随
一个jquery写的 导航条,横线跟随
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>一个jquery写的 导航条,横线跟随</title>
<script src="http://cdn.bootcss.com/jquery/1.8.2/jquery.js"></script>
<script>
$(function() {
/* ------------- mainNavA ------------- */
$('.mainNavA').each(function() {
var $box = $(this);
var $li = $box.find('li');
$hover_line = $('<div class="hover_line"></div>').appendTo($box);
$li.on('mouseenter',function() {
$(this).addClass('hover').siblings().removeClass('hover');
var w = $(this).outerWidth();
var left = $(this).position().left;
$hover_line.stop().animate( {
width:w,left:left
}
,200 );}).on('click',function() {
$(this).addClass('active').siblings().removeClass('active');
}
);
$box.mouseleave(function() {
var $nav_active = $box.find('li.active');
if($nav_active.length) {
$nav_active.addClass('hover').siblings().removeClass('hover');
var w = $nav_active.outerWidth();
var left = $nav_active.position().left;
$hover_line.stop().animate( {
width:w,left:left
}
,200 );}console.log('mouseleave');}).mouseleave();});
/* ------------- mainNavA end ------------- */})
</script>
<style>
a {
text-decoration:none;
}
ul,li {
margin:0px;
padding:0px;
list-style:none;
}
/*--------------------- .mainNavA --------------------------------*/
.mainNavA {
position:relative;
padding:0px 20px;
height:70px;
line-height:70px;
border-bottom:1px solid #e1e4e8;
background:#ffffff;
}
.mainNavA li {
float:left;
padding:0px 10px;
font-size:14px;
color:#444444;
margin-right:20px;
}
.mainNavA a {
color:#444444;
}
.mainNavA .hover a,.mainNavA a:hover {
color:#309ff4;
text-shadow:1px 1px 1px #acd9fb;
text-decoration:none;
}
.mainNavA .active.hover a {
font-weight:bold;
}
.mainNavA .hover_line {
height:2px;
overflow:hidden;
background:#309ff4;
position:absolute;
bottom:-1px;
}
/*--------------------- .mainNavA end --------------------------------*/
</style>
</head>
<body>
<!--html-->
<div class="mainNavA">
<ul>
<li><a href="#">栏目</a></li>
<li><a href="#">栏目标</a></li>
<li><a href="#">栏目标题</a></li>
<li class="active"><a href="#">栏目标题栏</a></li>
<li><a href="#">栏目标题栏目标题栏目标题</a></li>
</ul>
<!--<div class="hover_line">jquery 会帮我生存的</div>-->
</div>
<!--\html-->
</body>
</html>
KindEditor:Ajax提交表单时获取不到HTML内容
当用Ajax提交表单时,KindEditor的内容获取不到,HTML数据获取不了
原因:当ajax提交时,KindEdito的HTML数据还没有同步到表单中来,那怎么去获取HTML数据呢?
—————————————————
KindEditor 4.x documentation:获取HTML数据
// 取得HTML内容
html = editor.html();
// 同步数据后可以直接取得textarea的value
editor.sync();
html = document.getElementById(‘editor_id’).value; // 原生API
html = K(‘#editor_id’).val(); // KindEditor Node API
html = $(‘#editor_id’).val(); // jQuery
// 设置HTML内容
editor.html(‘HTML内容’);
—————————————————-
从这可看出,当Ajax提交表单时,textarea的value还是空的,需要使用sync()去同步HTML数据
那么在什么时候去同步,怎么同步?KindEditor同时提供了方法:
afterBlur
编辑器失去焦点(blur)时执行的回调函数。
数据类型: Function
默认值: 无
最后答案和解决办法:
<script type="text/javascript">
KindEditor.ready(function (K) {
window.editor = K.create('#AContent', {
afterBlur: function () { this.sync(); }
});
});
</script>
jquery返回顶部经典代码gotop.js
jquery返回顶部经典代码
jquery部分:
$(function(){
var w1 = 1100;//页面宽度
var w2 = $(window).width();
var w3 = (w1+w2)/2;
var $gotop = $('<a href="#" class="gotop" style="position:fixed; bottom:50px;">返回顶部</a>');
if(w1 < w2){
$gotop.css('left', w3 );
}else{
$gotop.css('right', 0 );
}
$("body").append($gotop);//向body底部 加入 返回顶部 链接
$(window).scroll(function(){
var h = $(document).scrollTop();
if( h < 100){
$gotop.fadeOut();;
}else{
$gotop.fadeIn();
}
}).scroll();
$gotop.click(function() {
$("body,html").animate({scrollTop:0},800);
return false;
});
});
css 改变外观:
.gotop{width:40px; height:40px; background:url(gotop.png) no-repeat 0px 0px;}
.gotop:hover{ background-position:0px -50px;}
gotop.png :
jquery插件框架
jquery插件框架
// JavaScript Document
(function($){
$.fn.extend({
//定义插件名称
pluginName: function(options){
// 插件开始 ---------------------------------------------
//默认参数
var defaults = {
/**参数 1 */
a:1,
/**参数 2 */
b:2,
/**参数 3 */
c:3
}
//参数合并
var options = $.extend(defaults, options);
return $(this).each(function( i , v ){
//针对每一个被选定的 元素操作 ----------- 功能 开始 -----------------
var o = options;// 在函数内部 就可以 用 o.a o.b o.c 调用参数
var $that = $(this);// $(this)
// 功能代码 ...
//针对每一个被选定的 元素操作 ----------- 功能 结束 -----------------
});
// 插件开始 ---------------------------------------------
}
});
})(jQuery);
调用插件
$('选择器').pluginName(json格式参数);
一个简单的双色li列表,基于jquery
一个简单的双色li列表,基于jquery
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>一个简单的双色li列表,基于jquery</title>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$('.dbcolor').each(function(){
$(this).children(':even').addClass('bg1');
$(this).children(':odd').addClass('bg2');
$(this).children().mouseover(function(){
$(this).addClass('hover');
}).mouseout(function(){
$(this).removeClass('hover');
});
});
});
</script>
<style>
.ulA li.bg1 { background:#f4f4f4;}
.ulA li.bg2 { background:#fff9c3;}
.ulA li.hover { background:#f88;}
.ulB li.bg1 { background:#f4f4f4;}
.ulB li.bg2 { background:#fff9c3;}
.ulB li.hover { background:#f88;}
</style>
</head>
<body>
<ul class="dbcolor ulA">
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
</ul>
<ul class="dbcolor ulB">
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
<li>一个简单的双色li列表,基于jquery</li>
</ul>
</body>
</html>