mutool

jesse62@163.com


  • 首页

  • 关于

  • 标签

  • 分类

  • 归档

puppeteer

发表于 2017-08-31 | 分类于 技术

关于 Puppeteer

一个Node库,它提供了一组高级API,通过DevTools协议控制无界面Chrome; 默认headless也就是无UI的chrome,也可以配置为有UI; 有点类似于PhantomJS,但Puppeteer是Chrome官方团队进行维护的,前景更好。
官网
GitHub
Chrome DevTools协议

阅读全文 »

鹰漠酒馆代码笔记

发表于 2017-02-26 | 分类于 技术

–MAC OS 启动–
打开多个终端
终端1:npm run mock 启动模拟api
终端2:npm run dev 启动页面
这样就可以跑起来了
或者iterm2 command+D 分出两个终端启动启动
– windows 启动–。
直接 npm run dev 会失败, 报错export是无效的命令==> package scripts里面import 改为 set
localhost:9090 和 0.0.0.0:8080 无效
127.0.0.1:9090 和 127.0.0.1:8080 访问
—Package—————————————————————————
$ npm install –save/–save-dev //–save生产环境 –save-dev开发环境
devDependencies 里面的插件只用于开发环境,不用于生产环境,而 dependencies 是需要发布到生产环境的。

$ npm install json-server //模拟API

package.json中的script来配置脚本,NODE_ENV代表node进程,或者说时环境变量
下面的mock和test就是配置的变量,node运行时执行对应的脚本
$ npm run mock //启动项目(通过json-server模拟json数据,本地运行)
$ npm run test //用于打包,上线

Babel是一个广泛使用的转码器,可以将ES6代码转为ES5代码,从而在现有环境执行。
// 转码前
input.map(item => item + 1);
// 转码后
input.map(function (item) {
return item + 1;
});
babel配置
{
“presets”: [
“es2015”,
“react”,
“stage-2”
],
“plugins”: []
}

$ npm install classnames –save-dev
在React中编写模板时给标签添加class。如果是固定的className=”XX”就可以了。
如果要根据状态值动态应用或去除,或使用多个class时就麻烦了。可以使用classnames模块来解决:
var classnames= require(‘classnames’);
classnames(‘foo’, ‘bar’); // => ‘foo bar’
classNames(‘foo’, { bar: true }); // => ‘foo bar’

$ npm install clean-webpack-plugin –save-dev
clean-webpack-plugin用于在building之前删除你以前build过的文件

$ npm install gulp-eslint –save-dev
EsLint帮助我们检查Javascript编程时的语法错误。比如:在Javascript应用中,你很难找到你漏泄的变量或者方法。
EsLint能够帮助我们分析JS代码,找到bug并确保一定程度的JS语法书写的正确性。

$ npm install whatwg-fetch –save
异步请求API
fetch(location.herf, {
method: “get”
}).then(function(response) {
return response.text()
}).then(function(body) {
console.log(body)
})

—Webpack.config.js—————————————————————–
$$ import path from ‘path’;
//NodeJS中的Path对象,用于处理目录的对象,提高开发效率。
1、格式化路径 path.normalize(p)
path.normalize(‘/foo/bar//baz/asdf/quux/..’);
特点:将不符合规范的路径格式化,简化开发人员中处理各种复杂的路径判断
=> ‘/foo/bar/baz/asdf’
2、路径合并 path.join([path1], [path2], […])
特点:将所有名称用path.seq串联起来,然后用normailze格式化
path.join(‘///foo’, ‘bar’, ‘//baz/asdf’, ‘quux’, ‘..’);
=>’/foo/bar/baz/asdf’
3、路径寻航 path.resolve([from …], to)
特点:相当于不断的调用系统的cd命令,调用cd是为创建文件夹
path.resolve(‘foo/bar’, ‘/tmp/file/‘, ‘..’, ‘a/../subfile’)
//相当于:
cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd
4、相对路径 path.relative(from, to)
特点:返回某个路径下相对于另一个路径的相对位置串,相当于:path.resolve(from, path.relative(from, to)) == path.resolve(to)
path.relative(‘C:\orandea\test\aaa’, ‘C:\orandea\impl\bbb’)
=>’..\..\impl\bbb’
path.relative(‘/data/orandea/test/aaa’, ‘/data/orandea/impl/bbb’)
=>’../../impl/bbb’
5、文件夹名称 path.dirname(p)
特点:返回路径的所在的文件夹名称
path.dirname(‘/foo/bar/baz/asdf/quux’)
=>’/foo/bar/baz/asdf’
……更多请百度

$ npm install precss –save
var precss = require(‘precss’);
Precss 可以在 CSS 文件中使用 Sass 类型的 Markup。

$ npm install autoprefixer –save
$$ import autoprefixer from ‘autoprefixer’;
Autoprefixer解析CSS文件并且添加浏览器前缀到CSS规则里,使用Can I Use的数据来决定哪些前缀是需要的
a{
transition :transform 1s
}
Autoprefixer使用一个数据库根据当前浏览器的普及度以及属性支持提供给你前缀:
a{
-webkit-transition :-webkit-transform 1s;
transition :-ms-transform 1s;
transition :transform 1s
}

$ npm install html-webpack-plugin –save
$$ import HtmlWebpackPlugin from ‘html-webpack-plugin’;
这个插件用来简化创建服务于 webpack bundle 的 HTML 文件,尤其是对于在文件名中包含了 hash 值,
而这个值在每次编译的时候都发生变化的情况,会生成html

$$ new webpack.optimize.CommonsChunkPlugin(‘common’, ‘bundle.js’),
CommonsChunkPlugin是提取公共代码块用的

$$ new webpack.optimize.UglifyJsPlugin({
$$ compress: {
$$ warnings: false,
$$ },
$$ })
UglifyJsPlugin是js代码压缩工具

$$ new webpack.optimize.OccurrenceOrderPlugin(),
根据模块调用次数,给模块分配ids,常被调用的ids分配更短的id,使得ids可预测,降低文件大小,该模块推荐使用
[ webpack 常用plugin和loader…https://segmentfault.com/a/1190000005106383 ]

$ npm whatwg-fetch –save
fetch(url).then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log(“Oops, error”, e))

—ES6…——————————————————————————-
Arrow Function(箭头函数) =>
x => x x
上面的箭头函数相当于:
function (x) {
return x
x;
}
箭头函数相当于匿名函数,并且简化了函数定义。
箭头函数有两种格式,一种像上面的,只包含一个表达式,连{ … }和return都省略掉了。
还有一种可以包含多条语句,这时候就不能省略{ … }和return:
x => {
if (x > 0) {
return x x;
}
else {
return - x
x;
}
}
箭头函数看上去是匿名函数的一种简写,但实际上,箭头函数和匿名函数有个明显的区别:
箭头函数内部的this是词法作用域,由上下文确定。
如果使用箭头函数,以前的那种hack写法:var that = this;
由于this在箭头函数中已经按照词法作用域绑定了,所以,
用call()或者apply()调用箭头函数时,无法对this进行绑定,即传入的第一个参数被忽略:
var obj = {
birth: 1990,
getAge: function (year) {
var b = this.birth; // 1990
var fn = (y) => y - this.birth; // this.birth仍是1990
return fn.call({birth:2000}, year);
}
};
obj.getAge(2015); // 25

FormData对象
通过 JavaScript 用一些键值对来模拟一系列表单控件
var oMyForm = new FormData();
oMyForm.append(“accountnum”, 123456); // 数字123456被立即转换成字符串”123456”

—app.jsx—————————————————————————-
let body = new FormData();
利用FormData对象,你可以使用一系列的键值对来模拟一个完整的表单,然后使用XMLHttpRequest发送这个”表单”.

—前端框架————————————————————————–
[浅谈移动前端的最佳事件…http://www.cnblogs.com/yexiaochai/p/4219523.html]
import ReactIScroll from ‘react-iscroll’
iscroll

有趣的题目

发表于 2016-10-11 | 分类于 题目

1.鸡兔同笼,共头35,脚96,求兔鸡各多少?

1
2
3
4
5
6
7
8
9
10
for(var rabit=0;rabit<25;rabit++){
if(rabit*4 + (35-rabit)*2 == 96){
console.log('兔子:'+rabit+',鸡:'+(35-rabit));
}
}

function tuotui(x,y){
return (y-x*2)/2;
}
tuotui(35,96);

2.一个篮子里有很多很多鸡蛋,2个2个拿多一个,3个3个拿多一个,4个4个拿多一个,5个5个拿多一个,6个6个拿多一个,7个7个刚刚好,篮子里有多少个鸡蛋?

1
2
3
4
5
6
for(var i=0;i<1000000;i++){
if(i%2==1 && i%3==1 && i%4==1 && i%5==1 && i%6==1 && i%7==0){
console.log(i);
break;
}
}

3.写一个函数,传入一个整数,判断是否为3的N次方,比如1,3,9,27…等返回true,否则返回false.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
//我的方法
function a(b){
var x=[],z=false;
for(var i=0;i<b;i++){
var y=(Math.pow(3,i)==b)?true:false;
x.push(y);
}
for(i in x){
if(x[i]){
z=x[i];
break;
}
}
console.log(x);
console.log(z);
}
//小寒的方法
function a(b){
for(var i=1;i<=b;i++){
if(Math.pow(3,i)==b){
return true;
}
}
return false;
}
//网上的方法
function isPowerOfThree(n){
if(n<0){
return false;
}
if(n==1){
return true;
}
//Math.log()方法可返回一个数的自然对数
var index = Math.log(n)/Math.log(3);
var cur = parseInt(index);//parseInt() 函数可解析一个字符串,并返回一个整数。
var next = Math.ceil(index);//ceil() 方法可对一个数进行上舍入。
if(n%3 == 0){
var temp = Math.pow(3,next) / n;
if(parseInt(temp) == temp){
return true;
}
}
return false;
}

4.给 array 对象添加一个原型方法,传入一个值,判断该数组中是否存在该值

1
2
3
4
5
6
7
Array.prototype.hasvalue=function(vue){ 
var returnvue=-1;
for(var i=0;i<this.length;i++){
if(vue==this[i]){ return i; }
}
return returnvue;
}

5.用两种方法实现打印 li 的索引(必须有闭包的方法)

1
2
3
4
5
6
7
8
9
10
window.onload = function () {
var aLi = document.getElementsByTagName("li");
for (var i = 0; i < aLi.length; i++) {
(function (i) {
aLi[i].onclick = function () {
alert(i);
};
})(i);
}
}

6.js 1234 实现 4321

1
2
var str="1234";
str.split("").reverse().join("");

APIClound项目JS代码片段

发表于 2016-07-12 | 分类于 技术
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//JSON下面的数组有长度
var json1={"abc":[{"name":"txt1"},{"name","txt2"}]};
for(var i=0;i<json1.abc.length;i++){alert(json1.abc[i].name);}
//json本身没有length属性
var json2={"name":"txt1","name2":"txt2"};

//获取Json的length
function getJsonLength(jsonData){
var jsonLength = 0;
for(var item in jsonData){
jsonLength++;
}
return jsonLength;
}

----------------------------------------------------

//getTime() 方法可返回距 1970 年 1 月 1 日之间的毫秒数。
//Date 对象用于处理日期和时间。
//setHours() 方法用于设置指定的时间的小时字段。
//parseInt() 函数可解析一个字符串,并返回一个整数。
----------------------------------------------------

//营业时间周一至周五,8:30-18:00
var a=new Date();
var b=new Date();
var c=new Date();
var week=c.getDay();
a.setHours(8,30,00);
b.setHours(18,00,00);
if(!(c>a && b>c) || week==0 || week==6){
c.setTime();
console.log(c);
}

----------------------------------------------------

//split() 方法用于把一个字符串分割成字符串数组

"2:3:4:5".split(":");
//将返回["2", "3", "4", "5"]

"|a|b|c".split("|") ;
//将返回["", "a", "b", "c"]


//Math.random()
//Math 对象用于执行数学任务。
//random() 方法可返回介于 0 ~ 1 之间的一个随机数。

----------------------------------------------------

//验证码
<input type="text" onclick="createCode()" readonly="readonly" id="checkCode" />
var code; //在全局 定义验证码
function createCode() {
code = "";
var codeLength = 6; //验证码的长度
var checkCode = document.getElementById("checkCode");
var selectChar = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'); //所有候选组成验证码的字符,当然也可以用中文的

for (var i = 0; i < codeLength; i++) {

var charIndex = Math.floor(Math.random() * 36);
code += selectChar[charIndex];

}
// alert(code);
if (checkCode) {
checkCode.className = "code";
checkCode.value = code;
}

}

//不区分大小写对比(验证码)
String.prototype.compare = function(str){
if(this.toLowerCase() == str.toLowerCase()){
return "1"; // 正确
}
else{
return "0"; // 错误
}
}

----------------------------------------------------

//倒计时,短信验证码
<input type="button" id="btn" value="免费获取验证码" />
<script type="text/javascript">
var wait=3;
function time(o) {
if (wait == 0) {
o.removeAttribute("disabled");
o.value="免费获取验证码";
wait = 3;
} else {
o.setAttribute("disabled", true);
o.value="重新发送(" + wait + ")";
wait--;
setTimeout(function() {
time(o)
},
1000)
}
}
document.getElementById("btn").onclick=function(){time(this);}
</script>

----------------------------------------------------

CSDN 代码迁移

发表于 2016-06-03 | 分类于 技术

表单验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
$("form :input.required").each(function(){
var $required = $("<strong class='high'>*</strong>");
$(this).parent().append($required);
});
$("form :input").blur(function(){
var $parent = $(this).parent();
$parent.find(".formtips").remove();
//验证用户名
if($(this).is('#username')){
if(this.value == "" || this.value.length < 6){
var errorMsg = '请输入至少6位的用户名.';
$parent.append("<span class='formtips onError'>"+errorMsg+"</span>");
}else{
var okMsg = '输入正确';
$parent.append('<span class="formtips onSuccess">'+okMsg+'</span>');
}
}
//验证邮箱
if($(this).is('#email')){
if(this.value=="" || (this.value!="" && !/.+@.+\.[a-zA-Z]{2,4}$/.test(this.value))){
var errorMsg = '请输入正确的E-Mail地址.';
$parent.append('<span class="formtips onError">'+errorMsg+'</span>');
}else{
var okMsg = '输入正确.';
$parent.append('<span class="formtips onSuccess">'+okMsg+'</span>');
}
}
}).keyup(function(){
$(this).triggerHandler("blur");
}).focus(function(){
$(this).triggerHandler("blur");
}); //keyup()和focus()即时判断,triggerHandler获取blur事件,但不执行blur()默认行为(即失去焦点)

$('#refer').click(function(){
$("form .required:input").trigger('blur'); //模拟失焦事件
var numError = $('form .onError').length;
if(numError){ //有值为true,0为false,
return false;
}
alert("注册成功,密码已发送到你的邮箱,请查收.");
});

翻页动画

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var page = 1;
var i = 3;
//下一页
$("span.next").click(function(){
var $parent = $(this).parents("div.v_show");
var $v_show = $parent.find("div.v_content_list");
var $v_content = $parent.find("div.v_content");

var v_width = $parent.width();
var len = $v_show.find("li").length;
var page_count = Math.ceil(len / i) //只要不是整数,就往大的方向取最小的整数,如3.1151 ~= 4;
if (!$v_show.is(":animated")) {
if (page == page_count) {
$v_show.animate({left: '0px'},"slow");

page = 1;
}else{
$v_show.animate({left: '-='+v_width},"normal");

page++;
}
$parent.find("span").eq((page - 1)).addClass("current")
.siblings().removeClass("current");
}
});
//上一页
$("span.prev").click(function(){
var $parent = $(this).parents("div.v_show");
var $v_show = $parent.find("div.v_content_list");
var $v_content = $parent.find("div.v_content");

var v_width = $parent.width();
var len = $v_show.find("li").length;
var page_count = Math.ceil(len / i) //只要不是整数,就往大的方向取最小的整数,如3.1151 ~= 4;
if (!$v_show.is(":animated")) {
if (page == 1) {
$v_show.animate({left: '-='+v_width*(page_count - 1)},"slow");

page = page_count
}else{
$v_show.animate({left: '+='+v_width},"normal");

page--;
}
$parent.find("span").eq((page - 1)).addClass("current")
.siblings().removeClass("current");
}
});

鼠标悬停图片预览,制作title提示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//图片预览
$(".imgtip li a").mouseover(function(e){
myTitle = this.title;
myHref = $(this).find("img").attr("src");
this.title="";
var imgtip = "<div id='imgtip'><img src='"+myHref+"'><br />"+myTitle+"</div>";

$("body").append(imgtip);
var h = $("#imgtip img").height();
$("#imgtip").css({
"position": "absolute",
"top": (e.pageY - h - 20) + "px",
"left": (e.pageX + 10) + "px"
}).show("fast");
}).mouseout(function(){
this.title = myTitle;
$("#imgtip").remove();
}).mousemove(function(e){
var h = $("#imgtip img").height();
$("#imgtip").css({
"top": (e.pageY - h - 20) + "px",
"left": (e.pageX + 10) + "px"
})
});

//title提示
$("a.tooltip").mouseover(function(e){
this.myTitle = this.title; //先存起来
this.title = ""; //再清空
var tooltip = "<div id='tooltip'>"+this.myTitle +"</div>";

$("body").append(tooltip);
$("#tooltip")
.css({
"position": "absolute",
"top": (e.pageY + 20) + "px",
"left": (e.pageX + 10) + "px"
}).show("fast");
}).mouseout(function(){
this.title = this.myTitle;
$("#tooltip").remove();
}).mousemove(function(e){
$("#tooltip")
.css({
"top": (e.pageY + 20) + "px",
"left": (e.pageX + 10) + "px"
})
});

Cookie网页更换皮肤

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var $li = $("#skin li");
//引用cookie,当用户刷新或关闭网页时,网页依然保持选中的皮肤(jquery.cookie.js)
$li.click(function(){
switchSkin(this.id)
});
var cookie_skin = $.cookie("MyCssSkin");
if(cookie_skin){ //如果确实存在Cookie
switchSkin(cookie_skin)
}
function switchSkin(skinName){
$("#"+skinName).addClass("selected")
.siblings().removeClass("selected");
$("#cssfile").attr("href","css/"+skinName+".css");
$.cookie("MyCssSkin",skinName,{path:'/',expires:10}); //计入cookie; $.cookie(名称,值,{路径,储存时间})
}

移动端font-size根据屏幕大小改变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//当设备的方向变化(设备横向持或纵向持)此事件被触发。绑定此事件时,
//注意现在当浏览器不支持orientationChange事件的时候我们绑定了resize 事件。
//总来的来就是监听当然窗口的变化,一旦有变化就需要重新设置根字体的值
var docEl = document.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function() {
docEl.style.fontSize = 16 * (docE1.clientWidth / 320) + 'px';
};
//绑定浏览器缩放与加载时间
window.addEventListener(resizeEvt, recalc, false);
document.addEventListener('DOMContentLoaded', recalc, false);

//根据实际情况通过设计稿与当前可视区的大小做一个比例关系,通过这个比例进行缩放处理
//给html设置fontSize大小,其实就是在DOMContentLoaded或者resize变化后调整fontSize的大小,从而调整rem的比值关系。

事件冒泡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//One()方法,为元素绑定处理函数,处理函数触发一次后,立即被删除
$("body").one("click",function(){
alert(1);
var txt = $("#msg").html() + "<p>body元素被点击。</p>";
$("#msg").html(txt);
});

$("#content").one("click",function(){
alert(2);
var txt = $("#msg").html() + "<p>content元素被点击。</p>";
$("#msg").html(txt);
});

$("#content span").bind("click",function(event){ //event:事件对象
alert(3);
var txt = $("#msg").html() + "<p>span元素被点击。</p>";
$("#msg").html(txt);
//event.stopPropagation(); //停止事件冒泡
//event.preventDefault() //阻止默认时间行为,如A标签的跳转,提交按钮等。
return false; //等同与上面的效果集合
});

百度富文本编辑器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var ue = UE.getEditor('editor'+j,{
toolbars: [[
'fullscreen', 'source', '|', 'undo', 'redo', '|',
'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
'directionalityltr', 'directionalityrtl', 'indent', '|',
'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
'link', 'unlink', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
'simpleupload', 'insertimage', 'emotion', 'scrawl', 'music', 'attachment','|',
'horizontal', 'date', 'time', 'spechars','|',
'inserttable', 'deletetable','mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', 'charts',
]],
autoHeightEnabled: true,
autoFloatEnabled: true,
initialStyle: 'p{line-height:1em; font-size: 16px; }',
initialContent: '',
autoClearinitialContent:true,
focus: false,
});
ue.addListener("contentChange",function(){
var s = ue.getContent();
if ($(s).length == "") {
var a = "<p>点此编辑『富文本』内容 ——&gt;</p><p>你可以对文字进行<strong>加粗</strong>、<em>斜体</em>、<span style='text-decoration: underline;'>下划线</span>、<span style='text-decoration: line-through;'>删除线</span>、文字<span style='color: rgb(0, 176, 240);'>颜色</span>、<span style='background-color: rgb(255, 192, 0); color: rgb(255, 255, 255);'>背景色</span>、以及字号<span style='font-size: 20px;'>大</span><span style='font-size: 14px;'>小</span>等简单排版操作。</p><p>还可以在这里加入表格了</p><table><tbody><tr><td width='93' valign='top' style='word-break: break-all;'>中奖客户</td><td width='93' valign='top' style='word-break: break-all;'>发放奖品</td><td width='93' valign='top' style='word-break: break-all;'>备注</td></tr><tr><td width='93' valign='top' style='word-break: break-all;'>猪猪</td><td width='93' valign='top' style='word-break: break-all;'>内测码</td><td width='93' valign='top' style='word-break: break-all;'><em><span style='color: rgb(255, 0, 0);'>已经发放</span></em></td></tr><tr><td width='93' valign='top' style='word-break: break-all;'>大麦</td><td width='93' valign='top' style='word-break: break-all;'>积分</td><td width='93' valign='top' style='word-break: break-all;'><a href='javascript: void(0);' target='_blank'>领取地址</a></td></tr></tbody></table><p style='text-align: left;'><span style='text-align: left;'>也可在这里插入图片、并对图片加上超级链接,方便用户点击。</span></p>"
$(".wb_txt").html(a);
} else {
$(".wb_txt").html(s);
}
});

确保jQuery库与其它库不发生冲突

1
2
3
4
5
6
7
8
9
(function($){				//定义匿名函数并设置形参为$
$(function(){ //匿名函数内部的$均为jQuery
$("p").click(function(){ //继续使用$()方法
alert($(this).text());
});
});
})(jQuery); //执行匿名函数且传递实参jQuery

$("pp").style.display = 'none'; //使用其它js库

三元运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
$('.tb2 > tbody > tr').click(function(){
//正常思路
if($(this).hasClass('selected')){
$(this)
.removeClass('selected')
.find(':checkbox').attr('checked','checked').prop('checked',false);
}else{
$(this)
.addClass('selected')
.find(':checkbox').attr('checked','').prop('checked',true);
}
//三元运算符
var hasSelected = $(this).hasClass('selected');
$(this)
[hasSelected?"removeClass":"addClass"]('selected') //三元运算符
.find(':checkbox').attr('checked',!hasSelected).prop('checked',!hasSelected);
});

简单的轮播图原理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
var silde = {
init:function(){
this.auto();
},
auto:function(){
var _root = this,
$ul = $("#sidle").find("ul"),
$lis = $ul.children("li"),
width = $lis.eq(0).width();
setInterval(function(){
$ul.animate({
'margin-left':'-' + width + 'px'
},
'slow',
function(){
//此处保证轮播循环
//将已经轮播过的节点的第一张图片添加到末尾的位置
//再将margin-left重置为0px;
//这样就能一直的循环下去。
$ul.css({'margin-left':0})
.children('li')
.last()
.after(
$ul.children('li').first()
);
});
},2000
);
}
};
silde.init();

JS设置cookie,删除cookie

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//页面一
<html>
<head>
<title>ex7</title>
<style type="text/css">
* {margin:0}
body {text-align:center;min-width:760px}
div {padding:3px 3px 3px 3px}
#main {width:720px;margin:0 auto;text-align:left;margin-top:30px}
#main div span {width:50px}
</style>

<script type="text/javascript">
/***
* @param {string} cookieName Cookie名称
* @param {string} cookieValue Cookie值
* @param {number} nDays Cookie过期天数
*/
function SetCookie(cookieName,cookieValue,nDays) {
/*当前日期*/
var today = new Date();
/*Cookie过期时间*/
var expire = new Date();
/*如果未设置nDays参数或者nDays为0,取默认值1*/
if(nDays == null || nDays == 0) nDays = 1;
/*计算Cookie过期时间*/
expire.setTime(today.getTime() + 3600000 * 24 * nDays);
/*设置Cookie值*/
document.cookie = cookieName + "=" + escape(cookieValue)
+ ";expires=" + expire.toGMTString();
}
function login() {
var username = $("user").value;
var password = $("pass").value;
/*是否选中7天内无需登录*/
var save = $("save").checked;
if(username=="sww" && password=="sww") {
if(save) SetCookie("username",username,7);
else SetCookie("username",username,1);
/*跳转到ex8.html页面*/
document.location = "ex8.html";
} else {
alert("用户名或密码错误!");
}
}
function $(id) {
return document.getElementById(id);
}
</script>
</head>
<body>
<div id="main">
<div><span>用户名:</span><input type="text" id="user" /></div>
<div><span>密码:</span><input type="password" id="pass" /></div>
<div>
<input type="checkbox" id="save" />
7天内无需登录
<input type="button" onclick="login()" value="登录" />
</div>
</div>
</body>
</html>

//页面二
代码

<html>
<head>
<title>ex8</title>
<script type="text/javascript">
/***
*读取指定的Cookie值
*@param {string} cookieName Cookie名称
*/
function ReadCookie(cookieName) {
var theCookie = "" + document.cookie;
var ind = theCookie.indexOf(cookieName);
if(ind==-1 || cookieName=="") return "";
var ind1 = theCookie.indexOf(';',ind);
if(ind1==-1) ind1 = theCookie.length;
/*读取Cookie值*/
return unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}

function $(id) {
return document.getElementById(id);
}

function init() {
var username = ReadCookie("username");
if(username && username.length>0) {
$("msg").innerHTML = "<h1>欢迎光临," + username + "!</h1>";
} else {
$("msg").innerHTML = "<a href='ex7.html'>请登录</a>";
}
}
</script>
</head>
<body onload="init()">
<div id="msg"></div>
</body>
</html>

仿猎聘网JQ代码片段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
//三元运算符
$(".change-city").on("click",function(){
$(this).hasClass("active")?($(this).removeClass("active"),$("#header-index .header-city-select").animate({top:0},200)):($(this).addClass("active"),$("#header-index .header-city-select").animate({top:"50px"},200))
});

//鼠标移入移出事件,仿hover
$(".drop-menu-group").mouseenter(function(){
}).mouseleave(function(){
})

//单个按钮,全选/取消全选
var $input = $(".item-list input[type=checkbox]");
var ary = new Array();
$input.change(function(){
if($(this).is(":checked")){
$(this).attr("i","0");
}else{
$(this).removeAttr("i");
}

$input.each(function(){
if($("[i=0]").length >= 3){
if($(this).attr("i") != 0){
$(this).attr("disabled",true);
}
}else{
$input.each(function(){
if($(this).attr("i") != 0){
$(this).removeAttr("disabled");
}
})
}
});
});

//循环DIV
function loop(a,b,c){
for(var i=0;i<c;i++){
$(a).append($(b).eq(0).clone(true))
}
}

(字体/高度)增大变小

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
var $comment = $("#comment");

$(".biggerHeight").click(function(){
if(!$comment.is(":animated")){
if($comment.height() < 500){
$comment.animate({height : "+=50"},400);
}
}
});
$(".smallerHeight").click(function(){
if(!$comment.is(":animated")){
if($comment.height() > 50){
$comment.animate({height : "-=50"},400);
}
}
});


//字体放大缩小
$(".msg_caption span").click(function(){
var thisEle = $("#para").css("font-size"); //获取字体大小
var textFontSize = parseInt(thisEle,10) //把获取的12px转换成数字类型12,10进制
var unit = thisEle.slice(-2); //获取单位,px,em均为后两位
var cName = $(this).attr("class");

if(cName == "biggerSize"){
if(textFontSize < 22){
textFontSize +=2;
}
}else if(cName == "smallerSize"){
if(textFontSize > 12){
textFontSize -=2;
}
}

$("#para").css("font-size",textFontSize+unit);
});

根据滚动条高度隐藏/显示(返回顶部)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//按钮绑定事件
$('#backTop').on('click',go);

//滚动条事件
$(window).on('scroll',function(){
checkPosition($(window).height()-200);
});

//返回顶部
function go(){
$('html,body').animate({scrollTop:0},800);
}

//检查滚动条位置
function checkPosition(pos){
if($(window).scrollTop() > pos){
$('#backTop').fadeIn();
}else{
$('#backTop').fadeOut();
}
}

//初始化检查
checkPosition($(window).height()-100);

向未来的元素添加事件处理程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// delegate() 方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。
// 使用
// delegate() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素)。

$(document).ready(function(){
$("div").delegate("p","click",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("<p>这是一个新段落。</p>").insertAfter("button");
});
});

// live() 方法为被选元素附加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。

// 通过 live() 方法附加的事件处理程序适用于匹配选择器的当前及未来的元素(比如由脚本创建的新元素)。
$(document).ready(function(){
$("p").live("click",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("<p>This is a new paragraph.</p>").insertAfter("button");
});
});

文字闪烁效果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
$(document).ready(function(){
function textFlash(obj,cssName,times){
var i=0,
t=false,
o=obj.attr("class"),
c="",
times=times||2; //如果没有设置闪烁次数,就默认为2次
if(t) return;
t=setInterval(function(){ //实现闪烁功能,通过setInterval()方法不停执行函数
i++; //i不断累加
c=i%2?o+cssName:o; //通过(i%2)切换class
obj.attr("class",c); //设置class来改变文本颜色
if (i==2*times) { //闪烁过程是一红一黑两个步骤,所以闪烁3次即切换2*3=6次
clearInterval(t); //清楚闪烁功能,即清除setInterval()方法
obj.removeClass(cssName); //恢复最初始颜色
};
},200);
};
$(function(){
//自动闪烁文本
textFlash($("#id-div-autoFlash"),"red",3);
//单机闪动文本
$("#id-div-clickFlash").bind({
click:function(){
textFlash($(this),"red",3);
return false;
}
});
//通过 E-mail 格式校验闪动文本
$("#id-input-emailFlash").blur(function(){
//使用正则表达式校验 E-mail 格式字符串
if(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test($(this).val())){
textFlash($(this),"red",3);
}
})
});
});
/*
.cssFlashred{color: red;}

<div id="id-div-autoFlash" class="cssFlash">文本自动闪烁</div>
<div id="id-div-clickFlash" class="cssFlash">单机文本闪烁</div>
<input id="id-input-emailFlash" class="cssFlash" type="email" placeholder="如果输入email地址会闪动" />
*/

jQuery页面加载后居中显示消息框的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function center(obj){
$.center=function(obj){
var screenWidth=$(window).width(); //当前浏览器窗口的宽度
var screenHeight=$(window).height(); //当前浏览器窗口的高度
var scrolltop=$(document).scrollTop(); //获取当前窗口距离页面顶部高度
var objLeft=(screenWidth-obj.width())/2;
var objTop=(screenHeight-obj.height())/2+scrolltop;
obj.css({
left:objLeft + 'px',
top:objTop + 'px',
display:'block'
});
}

$.center(obj);

$(window).resize(function(){
$.center(obj);
});
$(window).scroll(function(){
$.center(obj);
})
}

兼容click和tap事件

1
2
3
4
5
6
//兼容click和tap事件, 调用时用$(selector).on(CLICK,fn);
var UA = window.navigator.userAgent;
var CLICK = 'click';
if(/iPad|iPhone|Android/.test(UA)){
CLICK = 'tap';
}

js防止脚本注入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function html_encode(str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/</g, "&lt;");
s = s.replace(/>/g, "&gt;");
s = s.replace(/ /g, "&nbsp;");
s = s.replace(/\'/g, "&#39;");
s = s.replace(/\"/g, "&quot;");
s = s.replace(/\n/g, "<br>");
return s;
}
function encode_html(str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/&lt;/g, "<");
s = s.replace(/&gt;/g, ">");
s = s.replace(/&nbsp;/g, " ");
s = s.replace(/&#39;/g, "\'");
s = s.replace(/&quot;/g, '\"');
s = s.replace(/<br>/g, "\n");
return s;
}
$(function () {
$("input,textarea").each(function () {
$(this).blur(function () {
var str = $(this).val();
$(this).val(html_encode(str));
}).focus(function () {
var str = $(this).val();
$(this).val(encode_html(str));
});
});
})

绑定事件,传递数据

1
2
3
4
5
6
$(function(){
$("#id").bind('click',{d1:'Jquery:',d2:'将事件和函数绑定到元素'},myBindFunc(e));
})
function myBindFunc(e){
$("#div-log").html($("#div-log").html+"<p>"+e.data.d1+e.data.d2+"</p>");
}

DIY手机端商城主页代码片段(jquery一些操作)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//当前元素定位
function pos(e){
//查询当前模块所处页面位置,设置模块属性位置
var y = $(e).offset().top;
var x = $(e).offset().left;
$(e).css("top",y);
$(e).css("left",x);
$("html,body").animate({scrollTop:y},0);
}


//图片上传后图显示
<img id="img_Photo" src="" />
<input type="file" onchange="onChangeFile(this)" />
function onChangeFile(sender){
var filename = sender.value;
if (filename == "") {
return "";
}
var ExName = filename.substr(filename.lastIndexOf(".") + 1).toUpperCase();
if (ExName == "JPG" || ExName == "BMP" || ExName == "GIF" || ExName == "PNG") {
//店招图片
document.getElementById("img_Photo").src = window.URL.createObjectURL(sender.files[0]);
}
else {
alert('请选择正确的图片格式!');
sender.value = null;
return false;
}
}

//rgb(10进制)转#fff(16进制)的方法
function RGBToHex(rgb) {
var regexp = /^rgb\(([0-9]{0,3})\,\s([0-9]{0,3})\,\s([0-9]{0,3})\)/g;
var re = rgb.replace(regexp, "$1 $2 $3").split(" ");//利用正则表达式去掉多余的部分
var hexColor = "#";
var hex = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'];
for (var i = 0; i < 3; i++) {
var r = null;
var c = re[i];
var hexAr = [];
while (c > 16) {
r = c % 16;
c = (c / 16) >> 0;
hexAr.push(hex[r]);
}
hexAr.push(hex[c]);
hexColor += hexAr.reverse().join('');
}
return hexColor;
}


//URL地址选取(爽爽挝咖)
var string = window.location.href;//获取url地址
var index = string.indexOf("=");//indexOf()返回字符串指定出现的位置
var str = string.substring(index + 1, string.length);//substring()方法用于提取字符串中介于两个指定下标之间的字符。
var num = str.replace(/[^0-9]/ig, ""); //从字符串中取数字

1元购代码片段

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var hotQuestion = document.getElementById("hotQuestion");
var list = hotQuestion.getElementsByTagName("li");
for(var i=0;i<list.length;i++){
list[i].onclick = function(k){
return function(){
for(var i=0;i<list.length;i++){
var curLi = list[i];
div = $api.last(curLi, 'div'),
span = $api.first(curLi, 'span');
if(i==k){
$api.attr(div, 'style', 'display:block');
$api.addCls(span, 'rotation');
}else{
$api.attr(div, 'style', 'display:none');
$api.removeCls(span, 'rotation');
}
}
};
}(i);
}

倒计时和累加时间

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
//倒计时
startTimeOut = function ($this, currMS, type) {
var m = 0;//分钟
var s = 0;//秒
var o = 0;//毫秒
var i = 0;//计数器
var v; //时钟对象

//var currTime = new Date();
//var endTime = new Date();
//endTime.setSeconds(endTime.getSeconds() + currMS/1000 - 1);
//var w = parseInt((endTime.getTime() - currTime.getTime()) / 1000);
var w = currMS/1000;
if (w < 0)
return;
m = parseInt(w / 60);
s = parseInt(w % 60);
o = (w == 0) ? currMS : 99;
this.countdown = function () {
v = setInterval(function() {
i++;
if (type == "singleLottery" && $("#singleLottery").attr("style").indexOf("top:0")<0) {
$("#singleLottery").attr("style", "top:0;position:relative;padding:0;margin:0;");//将滚动条还原到第一行,此处避免滚动中的回零失效问题
}
if (m <= 0 && s <= 0 && o <= 0) {
//开始揭晓 spanTime1
clearInterval(v);
refreshLottery($this,type);
return;
}
o = o - Math.round(Math.random() * 19 + 1);

if (i >= 5) {
i = 0;
//Math.round(Math.random()*9+1);
s = s - 1;
/*if (s == 0 && m > 0)
m = m - 1;
else if (s < 0 && m > 0)
s = 59;*/
if (s <= 0 && m > 0) {
s = 59;
m = m - 1;
}
if (m <= 0 && s <= 0)
o = 0;
if (m > 0 || s > 0)
o = 99;
}
if (m <= 0) m = 0;
if (s <= 0) s = 0;

var mStr = m < 10 ? ('0' + m) : m;
var sStr = s < 10 ? ('0' + s) : s;
var oStr = o < 10 ? ('0' + o) : o;
$this.html(mStr + ":" + sStr + ":" + oStr);
}, 200);
timer.push(v);
}
}


//时间累加计算方法 2017-01-09 16:45 Jesse
function HaveOrderTime(timeBox,currMS) {
var d,h,m,s;
var AS = parseInt(currMS / 1000);
if(AS > 0){
if(AS > 59){//秒
if(parseInt(AS / 60) > 59){//分
if(parseInt(AS / 3600) > 24){//小时
s=parseInt(AS % 86400 % 3600 % 60);
m=parseInt(AS % 86400 % 3600 / 60);
h=parseInt(AS % 86400 / 3600);
d=parseInt(AS / 86400);
}else{
s=parseInt(AS % 3600 % 60);
m=parseInt(AS % 3600 / 60);
h=parseInt(AS / 3600);
d=0;
}
}else{
s=parseInt(AS % 60);
m=parseInt(AS / 60);
d=h=0;
}
}else{
s = AS;
d=h=m=0;
}
}else{
return;
}
console.log(d+','+h+','+m+','+s);
setInterval(function() {
s++;
if(s > 59){
if(m+1>59){
if(h+1>24){
d++;
h=m=s=0;
}else{
h++;
m=s=0;
}
}else{
m++;
s=0;
}
}
var txt=dStr=hStr=mStr=sStr='';
if(s>0)sStr =s+'秒';
if(m>0)mStr =m+'分';
if(h>0)hStr =h+'小时';
if(d>0)dStr =d+'天';

timeBox.textContent = dStr+hStr+mStr+sStr;
}, 1000);
}

募才网移动端表单验证

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
$("input[type=text]").focus(function () {
$(this).prev("p").find("span").text("");
})
var flag;
var pat = new RegExp("^[A-Za-z0-9]+$");
function check() {
flag = true;
var password = $("#TextBox2").val().trim();
var comfirm = $("#TextBox3").val().trim();
checkIt("#TextBox1", '请输入至少 6 位的用户名', '用户名由字母、数字组成');
checkIt("#TextBox2", '请输入至少 6 位的密码', '密码由字母、数字组成');
if ($("#txtt").val() == "2") {
if (comfirm == "") {
$("#TextBox3").prev("p").find("span").text("确认密码不能为空");
flag = false;
} else if (comfirm != password) {
$("#TextBox3").prev("p").find("span").text("两次密码输入不一致");
flag = false;
}
}
return flag;
}

function checkIt(id, msg1, msg2) {
var val = $(id).val().trim();
if (val == "" || val.length < 6) {
var errorMsg = msg1;
flag = false;
} else if (!pat.test(val)) {
var errorMsg = msg2;
flag = false;
}
if (flag == false) {
$(id).prev("p").find("span").text(errorMsg);
}
}

jQuery实用的代码片段

发表于 2016-05-27 | 分类于 技术
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//1.页面加载完之前执行,与嵌入的JS加载方式一样
(function($){
alert("start");
})(jQuery);
//2.页面加载完后执行
$(document).ready(function(){
alert("jquery ready");
});
//3.页面加载完后执行
$(function(){
alert("jquery onload");
});
//4.页面加载完后执行
jQuery(function($){
alert("jquery ready");
});

//修改jQuery默认编码
$.ajaxSetup({
ajaxSettings:{contentType:"application/x-www/form-urlencoded;charset=GB2312"}
});

//检查各种浏览器
//1.检查Safari:
(if($.browser.safari))
//2.检查IE6及之后版本:
(if($.browser.msie && $.browser.version>6))
//3.检查IE6及之前版本:
(if($.browser.msie && $.browser.version<=6))
//4.检查FireFox2及之后版本:
(if($.browser.mozilla && $.browser.version>='1.8'))

//选中页面上的所有复选框
var tog=false;
$("a").click(function(){
$("input[type=checkbox]").attr("checked",!tog);
tog=!tog;
});

//返回顶部代码
$(document).ready(function(){
jQuery.scrollTo=function(scrollDom,scrollTime){
$(scrollDom).click(function(){
$('html,body').animate(
{
scrollTop:$(scrollDom).offset().top
},
scrollTime
);
return false;
});
};
$.scrollTo("a",1000);
})

//iframe高度自适应
$(document).ready(function(){
$("iframe").load(function(){
var vHeight=$(this).contents().find("body").height() + 32;
$(this).height(vHeight<300?300:vHeight);
});
});
<iframe src="1.html" frameborder="0" scrolling="no"></iframe>

//左右DIV自适应相同高度
function $(id){
return document.getElementById(id);
}
function autoHeight(){
if($("left").offsetHeight >= $("right").offsetHeight){
$("right").style.height=$("left").style.height + "px";
}else{
$("left").style.height=$("right").style.height + "px";
}
}
window.onload=function(){
autoHeight();
}

//获取鼠标的位置
$(document).ready(function(){
$(document).mouse(function(e){
getScreenCoordinates(e); //调用函数
});
});
function getScreenCoordinates(e){
//在屏幕中
x=e.screenX;
y=e.screenY;
//在窗口客户区
x=e.clientX;
y=e.clientY;
//在窗口页面中
x=e.pageX;
y=e.pageY;

$("span").text("X:"+x+",Y:"+y+);
}

CSS 摘抄

发表于 2016-05-26 | 分类于 技术
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/*清楚浮动*/
.clearfix{
*zoom:1;
_height:1px;
}
.clearfix:before,
.clearfix:after {
display: table;
line-height: 0;
content: "";
}

/*文字选中不高亮*/
.noselect{
-webkit-touch-callout:none;
-webkit-user-select:none;
-khtml-user-select:none;
-moz-user-select:none;
-ms-user-select:none;
user-select:none;
}

/*改变input[type="text"]的placeholder颜色*/
::-webkit-input-placeholder{
color:#999;
}
:-moz-placeholder{
color:#999;
opacity:1;
}
::-moz-placeholder{
color:#999;
opacity:1;
}
:-ms-input-placeholder{
color:#999;
}

/*水平垂直居中*/
div{
display:table;
width:250px;
height:100px;
text-align:center;
}
div span{
display:table-cell;
vertical-align:middle;
}

HTML meta 标签

发表于 2016-05-26 | 分类于 技术
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<meta charset='utf-8'>
<!-- 声明文档使用的字符编码 -->

<html lang="zh-cmn-Hans">
<!-- 更加标准的 lang 属性写法 http://zhi.hu/XyIa -->

<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<!-- 优先使用 IE 最新版本和 Chrome -->

<meta name="renderer" content="webkit">
<!-- 360使用Google Chrome Frame,360 浏览器就会在读取到这个标签后,立即切换对应的极速核 -->

<meta http-equiv="Cache-Control" content="no-siteapp" />
<!-- 百度禁止转码 -->

<meta name="keywords" content="your keywords">
<!-- 页面关键词 keywords -->

<meta name="description" content="your description">
<!-- 页面描述内容 description -->

<meta name="author" content="author,email address">
<!-- 定义网页作者 author -->

<meta name="robots" content="index,follow" />
<!-- 搜索引擎抓取 -->


<!-- 移动端 -->
<meta name ="viewport" content ="initial-scale=1, maximum-scale=3, minimum-scale=1, user-scalable=no">
<!-- 为移动设备添加 viewport -->

<meta name="apple-mobile-web-app-capable" content="yes" />
<!-- 是否启用 WebApp 全屏模式 -->

<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<!-- 设置状态栏的背景颜色,只有在 `"apple-mobile-web-app-capable" content="yes"` 时生效 -->

<meta name="format-detection" content="telephone=no" />
<!-- 禁止数字识自动别为电话号码 -->

<link rel="shortcut icon" type="image/ico" href="/favicon.ico" />
<!-- 添加 favicon icon -->

<meta name="google" value="notranslate" />
<!-- 禁止谷歌翻译 -->

原生JS的一些操作

发表于 2016-05-03 | 分类于 技术
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
window.onload = function(){
//判断是否选中
var $cr = $("#cr"); //jquery对象
var cr = $cr[0]; //DOM对象,或者$cr.get(0);
$cr.click(function(){
if (cr.checked) { //DOM的方式判断
alert("感谢你的支持!你可以继续操作!JS");
}
if($cr.is(":checked")){ //Jquery的方式判断
alert("感谢你的支持!你可以继续操作!JQ");
}
});


//是否勾中全选
$("[name=items]:checkbox").change(function(){
var flag = true;
$("[name=items]:checkbox").each(function(){
if(!this.checked){
flag = false;
}
});
$("#checkAllNo").attr("checked",flag).prop("checked",flag);
});


//选中当前并添加class
var div = document.getElementsByClassName("jsp")[0];
var items = div.getElementsByTagName("p");
for (var i=0;i < items.length;i++) {

items[i].onclick = function(){
var pls = this.parentNode.childNodes;

for (var i=0;i < pls.length;i++) {
pls[i].className = "";
}

this.className = "selected";
}
}


//隔行换色
var tb = document.getElementById("tb"); //获取ID为tb的元素(ID是唯一属性,不用加索引[0])
var tbody = tb.getElementsByTagName("tbody")[0];
var tr = tbody.getElementsByTagName("tr");
for (var i=0;i < tr.length;i++) {
if(i%2 == 0){ //取模(取余数。例如0%2=0,1%2=1,2%2=0;3%2=1)
tr[i].style.backgroundColor = "#f00";
}
}


//判断选中个数
<div>
<input type="checkbox" value="1" name="check" checked="checked" />
<input type="checkbox" value="2" name="check" />
<input type="checkbox" value="2" name="check" checked="checked" />
<input type="button" id="btn" value="你选中的个数" />
</div>
var btn = document.getElementById("btn");
btn.onclick = function(){
var ary = new Array(); //创建一个数组对象
var ipt = document.getElementsByName("check");

for (var i=0;i < ipt.length;i++) {
if (ipt[i].checked) { //判断是否被选中
ary.push(ipt[i].value); //把符合条件的添加到数组当中,push()是javascript中数组的方法
}
}
alert("选中的个数为:"+ ary.length)
}


//当前P在所有P元素中的索引值
<div class="numindex">
<p>11111111</p>
<div>11111111</div>
<p>11111111</p>
<div>11111111</div>
<p>11111111</p>
<div>11111111</div>
</div>
//JS方法
var box = document.getElementsByClassName("numindex")[0];
var p = box.getElementsByTagName("p");
for(i = 0 ; i<p.length;i++){
(function(k){
p[i].onclick=function(){
alert(k);
}
})(i);
}
//JQ方法
$(".numindex p").each(function(){
$(this).addClass("a "+$(this).index());
var arr = $(".a");
$(this).click(function(){
var b = $(this).index();
alert(arr.index($("."+b)));
});
});
}

使用Hexo搭建个人博客

发表于 2016-03-22 | 分类于 前端开发
本文用于记录使用Hexo搭建个人博客的流程.
阅读全文 »
123

文杰

30 日志
4 分类
26 标签
© 2019 文杰
由 Hexo 强力驱动
|
主题 — NexT.Pisces v5.1.4