js特殊用法

jquery

获取json

JS里使用 $!{string} 获取原格式的字符串;

出现此种错误时,将*${}* 改为*$!{}* 使用

js 动态元素选择器

1
2
3
var i=1;
var head="head"+i;
$("#head"+head+"");

使用js处理双击、选中事件

jquery 处理方式

1
$(document.body).on('mouseup',"#content",mouseUp);

dom处理方式:

1
2
document.addEventListener("dblclick", doubleClick, true);

释放鼠标处理函数

1
2
3
4
5
6
7
8
9
10
11
12
function mouseUp() {
var text = "";
if (window.getSelection) {
text = window.getSelection().toString();
} else if (document.selection && document.selection.type != "Control") {
text = document.selection.createRange().text;
}
if ("" != text&&" " != text) {
$("#checkText").val(text);
layer.msg(text);
}
}

js计算

1
2
3
4
parseInt(5/2); 结果:2 舍弃小数部分,取整数
Math.ceil(5/2); 结果:3 向上取整,有小时就整数加一
Math.round(5/2);结果:3 四舍五入
Math.floor(5/2);结果:2 向下取整

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
34
35
36
37
38
39
40
41
42
43
44
45
function getLineNum(){

var $lineNum=$("#lineNum");

$lineNum.empty();

var rowNum=Math.round(document.getElementById("contentT").scrollHeight/parseFloat($("#contentT").css("line-height")));

console.log("$('.article fl').height():"+document.getElementById("contentT").scrollHeight);

console.log("parseFloat($('.article fl').css('line-height')):"+parseFloat($("#contentT").css("line-height")));

console.log(rowNum);

for(var i=1;i<rowNum;i++){
var flag=false;
if(headNum>1){
for(var j=2;j<=headNum;j++){
var headId="head"+j;
var $headEle=$("#"+headId+"");
var offsetTop=$headEle.position().top;
var headRow=Math.round(offsetTop/parseFloat($("#contentT").css("line-height")));
headRow=headRow+1;
if(headRow==i){
flag=true;
break;
}
}
}
if(flag){
if(i%5==0||i==1){
$lineNum.append("<br><p>"+i+"</p>");
}else{
$lineNum.append("<br><br>");
}
}else{
if(i%5==0){
$lineNum.append("<p>"+i+"</p>");
}else if(i==1){
$lineNum.append("<p>"+i+"</p>");
}else{
$lineNum.append("<br>");
}
}
}};

js对象转换

jquery对象<->dom对象

dom对象转换为jquery对象:
1
2
var d=document.getElementById("id");	//对象d为DOM对象
var s=$(d); //对象s为Jquery对象
jquery对象转换为dom对象:
1
2
3
var d=document.getElementById("id");   //对象d为DOM对象
var s=$(d); //对象s为Jquery对象
var dd=s.get(0) //对象dd为DOM对象

js随机打乱数组

1
2
3
4
5
6
7
function randomsort(a, b) {
return Math.random()>.5 ? -1 : 1;
//用Math.random()函数生成0~1之间的随机数与0.5比较,返回-1或1
}
var arr = [1, 2, 3, 4, 5];
arr.sort(randomsort);

js从数组中获取指定个数的随机数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/**
* 从数组中随机取指定数量的数据
* @param arr 数据
* @param count 随机数量
* @returns {*}
*/
function getRandomArrayElements(arr, count) {
var shuffled = arr.slice(0), i = arr.length, min = i - count, temp, index;
while (i-- > min) {
index = Math.floor((i + 1) * Math.random());
temp = shuffled[index];
shuffled[index] = shuffled[i];
shuffled[i] = temp;
}
return shuffled.slice(min);
}

js禁止双击

1
2
<body onselectstart = "return false" style = { -moz-user-select : none }></body>

js控制div里的滚动条

1
2
$('.dtcon').animate({scrollTop:'0px'}, 200);
200:滚动条移动至指定位置所需时间 ms