包含了html和JavaScript常用的一些特殊方法。
目录:
1. 跳转至页面指定元素处
<a href="#id"></a>
即将href中的地址写成#加上要跳转至的元素的id,#id
;
2. HTML焦点事件
2.1 定义HTML焦点事件
<input onfocus="" onblur="" />
onfocus和onblur分别是获得焦点和失去焦点事件
2.2 js赋予HTML元素获得焦点
document.getElementById("elemId").focus;
2.3 js赋予input/textarea元素焦点并移动焦点至最后一个位置
var el = document.getElementById('elemId');
if(el.setSelectionRange){
el.focus();
el.setSelectionRange(el.value.length,el.value.length);
}else{
var range = el.createTextRange();
range.collapse(false);
range.select();
}
3. js控制HTML元素的隐藏和显示
3.1 最简单的隐藏操作–hidden属性
document.getElementById("elemId").hidden="hidden";
3.2 仅隐藏html元素,原控件处显示空白
document.getElementById("elemId").style.visibility='hidden';
document.getElementById("elemId").style.visibility="visible";
3.3 隐藏html元素,原控件不占用位置
document.getElementById("elemId").style.display="none";//隐藏
document.getElementById("elemId").style.display="inline"//显示
4. js数组
var array = new Array(); //or:new Array(size), new Array(element0,...,elementN)
var length = array.length;
array.push(element); //add element to the last and return new length
array.pop(); //delete and return the last element in array
具体可参照:JavaScript Array对象
5. 常用js方法
5.1 时间戳转格式化时间
/**
* 将时间戳转换成常用的日期格式,
* 如:1970-01-17 23:01:53
* @param timeStamp
* @returns
*/
function parseTimeStamp(timeStamp){
var time = new Date(timeStamp);//传入的timeStamp为整数,否则要parseInt
var year = time.getFullYear();
var month = time.getMonth()+1;
var day = time.getDate();
var hour = time.getHours();
var minute = time.getMinutes();
var second = time.getSeconds();
var tt = year+'-'+add0(month)+'-'+add0(day)+' '
+add0(hour)+':'+add0(minute)+':'+add0(second);
return tt;
}
function add0(m){return m<10?'0'+m:m };
5.2 获得当前网站根路径
/**
* 获取网站当前根路径
* @returns
*/
function getRootPath() {
// 获取当前网址,如:http://localhost/WebCourse/jsp/login/login.jsp
var curWwwPath = window.document.location.href;
// 获取主机地址之后的目录,如:/ WebCourse/jsp/login/login.jsp
var pathName = window.document.location.pathname;
var pos = curWwwPath.indexOf(pathName);
// 获取主机地址,如: http://localhost
var localhostPath = curWwwPath.substring(0, pos);
// 获取带"/"的项目名,如:/WebCourse
var projectName = pathName.substring(0,
pathName.substr(1).indexOf('/') + 1);
return (localhostPath + projectName);
}
6.html动态引入公共html
thymeleaf中,使用
<div th:fragment="tagName"></div>
包含html,在主HTML中使用<div th:replace="path::tagName"></div>
引入tagName定义的html;也可以使用<div th:include="path::tagName"></div>
//要引入的html:shared/head.html
<html xmlns:th="http://www.thymeleaf.org">
<meta charset="UTF-8" />
<body>
<div th:fragment="head">
<span>this is the html to import.</span>
</div>
</body>
</html>
//引入上面的html
<div th:replace="/shared/head::head"></div>
//or
<div th:include="/shared/head::head"></div>
7.js定义回车事件
//回车事件
$('#newsKeyword').bind('keyup', function(event) {
if(event.keyCode == "13") {
$('#newsSearchButton').click();
}
});