// querySelector() 返回匹配到的第一个元素var item = document.querySelector('.item')console.log(item)// querySelectorAll() 返回匹配到的所有元素,是一个nodeList集合var items = document.querySelectorAll('.item')console.log(items[0])1234567
阻止默认行为
// 原生jsdocument.getElementById('btn').addEventListener('click', function (event) {event = event || window.event;if (event.preventDefault){// w3c方法 阻止默认行为
event.preventDefault()
} else{// ie 阻止默认行为
event.returnValue = false
}
}, false)// jQuery$('#btn').on('click', function (event) {event.preventDefault()
})1234567891011121314151617
阻止冒泡
// 原生jsdocument.getElementById('btn').addEventListener('click', function (event) {event = event || window.event;if (event.stopPropagation){// w3c方法 阻止冒泡
event.stopPropagation()
} else{// ie 阻止冒泡
event.cancelBubble = true
}
}, false)// jQuery$('#btn').on('click', function (event) {event.stopPropagation()
})1234567891011121314151617
鼠标滚轮事件
$('#content').on("mousewheel DOMMouseScroll", function (event) {
// chrome &ie || // firefox
var delta = (event.originalEvent.wheelDelta &&(event.originalEvent.wheelDelta >0 ? 1 : -1)) || (event.originalEvent.detail &&(event.originalEvent.detail >0 ? -1 : 1))
if (delta >0) {
// 向上滚动
console.log('mousewheel top')
} else if (delta <0) {// 向下滚动
console.log('mousewheel bottom')
}
})123456789101112
检测浏览器是否支持svg
function isSupportSVG() {
var SVG_NS = 'http://www.w3.org/2000/svg' return !!document.createElementNS &&!!document.createElementNS(SVG_NS, 'svg').createSVGRect
}
// 测试console.log(isSupportSVG())1234567
检测浏览器是否支持canvas
function isSupportCanvas() {
if(document.createElement('canvas').getContext){return true
}else{return false
}
}// 测试,打开谷歌浏览器控制台查看结果console.log(isSupportCanvas())12345678910
检测是否是微信浏览器
function isWeiXinClient() {
var ua = navigator.userAgent.toLowerCase()
if (ua.match(/MicroMessenger/i)=="micromessenger") {
return true
} else {
return false
}
}// 测试alert(isWeiXinClient())1234567891011
jQuery 获取鼠标在图片上的坐标
$('#myImage').click(function(event){
//获取鼠标在图片上的坐标
console.log('X:' + event.offsetX+'\n Y:' + event.offsetY)
//获取元素相对于页面的坐标
console.log('X:'+$(this).offset().left+'\n Y:'+$(this).offset().top)
})1234567
验证码倒计时代码
<!-- dom --><input id="send" type="button" value="发送验证码">12
// 原生js版本var times = 60, // 临时设为60秒
timer = null
document.getElementById('send').onclick = function () {
// 计时开始
timer = setInterval(function () {
times-- if (times <= 0) {
send.value = '发送验证码'
clearInterval(timer)
send.disabled = false
times = 60
} else {
send.value = times + '秒后重试'
send.disabled = true
}
}, 1000)
}1234567891011121314151617181920
// jQuery版本var times = 60,
timer = null
$('#send').on('click', function () {
var $this = $(this) // 计时开始
timer = setInterval(function () {
times-- if (times <= 0) {
$this.val('发送验证码')
clearInterval(timer)
$this.attr('disabled', false)
times = 60
} else {
$this.val(times + '秒后重试')
$this.attr('disabled', true)
}
}, 1000)
})12345678910111213141516171819202122
常用的一些正则表达式
//匹配字母、数字、中文字符
/^([A-Za-z0-9]|[\u4e00-\u9fa5])*$/
//验证邮箱
/^\w+@([0-9a-zA-Z]+[.])+[a-z]{2,4}$/
//验证手机号
/^1[3|5|8|7]\d{9}$/
//验证URL
/^http:\/\/.+\./
//验证身份证号码
/(^\d{15}$)|(^\d{17}([0-9]|X|x)$)/
//匹配中文字符的正则表达式
/[\u4e00-\u9fa5]/
//匹配双字节字符(包括汉字在内)
/[^\x00-\xff]/1234567891011121314151617181920
js时间戳、毫秒格式化
function formatDate(now) {
var y = now.getFullYear() var m = now.getMonth() + 1// 注意js里的月要加1
var d = now.getDate() var h = now.getHours()
var m = now.getMinutes()
var s = now.getSeconds() return y + "-" + m + "-" + d + " " + h + ":" + m + ":" + s
}
var nowDate = new Date(2016, 5, 13, 19, 18, 30, 20)
console.log(nowDate.getTime())// 获得当前毫秒数: 1465816710020console.log(formatDate(nowDate))123456789101112131415
js限定字符数(注意:一个汉字算2个字符)
<input id="txt" type="text">//字符串截取function getByteVal(val, max) {
var returnValue = '' var byteValLen = 0 for (var i = 0i <val.lengthi++) {if (val[i].match(/[^\x00-\xff]/ig) != null) byteValLen += 2else byteValLen += 1 if (byteValLen >max) break
returnValue += val[i]
}return returnValue
}
$('#txt').on('keyup', function () {
var val = this.value if (val.replace(/[^\x00-\xff]/g, "**").length >14) {this.value = getByteVal(val, 14)
}
})12345678910111213141516171819
js判断是否移动端及浏览器内核
var browser = {
versions: function() {
var u = navigator.userAgent
return {
trident: u.indexOf('Trident') >-1, //IE内核
presto: u.indexOf('Presto') >-1, //opera内核
webKit: u.indexOf('AppleWebKit') >-1, //苹果、谷歌内核
gecko: u.indexOf('Firefox') >-1, //火狐内核Gecko
mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端
ios: !!u.match(/\(i[^]+( U)? CPU.+Mac OS X/), //ios
android: u.indexOf('Android') >-1 || u.indexOf('Linux') >-1, //android
iPhone: u.indexOf('iPhone') >-1 , //iPhone
iPad: u.indexOf('iPad') >-1, //iPad
webApp: u.indexOf('Safari') >-1 //Safari
}
}
}
if (browser.versions.mobile() || browser.versions.ios() || browser.versions.android() || browser.versions.iPhone() || browser.versions.iPad()) {
alert('移动端')
}123456789101112131415161718192021
之前我用过一个检测客户端的库 觉得挺好用的,也推荐给大家 叫 device.js,大家可以 Googel 或 百度
GItHub仓库地址:https://github.com/matthewhudson/device.js
getBoundingClientRect() 获取元素位置
//它返回一个对象,其中包含了left、right、top、bottom四个属性var myDiv = document.getElementById('myDiv')var x = myDiv.getBoundingClientRect().left
var y = myDiv.getBoundingClientRect().top
// 相当于jquery的: $(this).offset().left、$(this).offset().top // js的:this.offsetLeft、this.offsetTop123456
HTML5全屏
function fullscreen(element) {
if (element.requestFullscreen) {
element.requestFullscreen()
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen()
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullscreen()
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen()
}}
fullscreen(document.documentElement)12345678910111213
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/htmlcharset=UTF-8">
<title>瀑布流以及回顶部的效果</title>
<style type="text/css">
*{
margin:0
padding:0
}
h1{
text-align:center
height:100px
}
body{
background-color:RGB(232,231,226)
}
.all{
margin:0 auto
width:1000px
}
.number{
float:left
width:225px
}
.content
{
margin:5px
background-color:white
}
img{
margin:5px
}
.loading{
position: absolute
width:100%
height:40px
display:none
text-align:center
background-color:RGB(189,203,207)
}
#toTop
{
position:fixed
_position:fixed
font-size:12px
color:Blue
width:15px
text-align:center
right:300px
bottom:100px
cursor:pointer
background-color:RGB(243,247,251)
display:none
}
</style>
<script type="text/javascript">
window.onload = function () {
//初始参数
var reset = 0//某些滚动条会触发三次scroll事件 用这个解决
var surplusHeight = 800//差值
var imgWidth = "206px"//img的宽度
var imgHeight = 0//img的高度
var textHeight = 0//文字高度
var showTopButtonHeight = 500//回到顶部按钮的距离
var bigDivCount = 4
var div1 = $("one")
var div2 = $("two")
var div3 = $("three")
var div4 = $("four")
var loading = $("loading")
var toTop = $("toTop")
//得到浏览器的名称
var browser = getBrowser()
//数据源
var imgArray = []//img数组 也就是数据来源
var textArray = []//img底下的文字和img对应
textArray[0] = "小花美女"
textArray[1] = "小花美女小花美女"
textArray[2] = "小花美女小花美女小花美女"
textArray[3] = "小花美女小花美女小花美女小花美女"
textArray[4] = "小花美女 小花美女"
textArray[5] = "小花美女小花小花美女"
textArray[6] = "小花美女"
textArray[7] = "小花美女小花美女"
textArray[8] = "小花美女小花美女小花美女"
textArray[9] = "小花美女小花美女小花美女小花美女小花美女"
textArray[10] = "小花美女小花美女小花美女小花美女小花美女"
textArray[11] = "小花美女小花美女小花美女小花美女小花美女小花美女"
textArray[12] = "小花美女小花美女小花美女小花美女小花美女小花美女小花美女"
textArray[13] = "小花美女小花美女小花美女小花美女小花美女小花美女小花美女小花美女"
textArray[14] = "小花美女小花美女小花美女小花美女小花美女小花美女小花美女小花美女"
textArray[15] = "小花美女小花美女小花美女小花美女小花美女小花美女小花美女小花美女"
imgArray[0] = "http://files.jb51.net/file_images/article/201211/960bda11tw1dnw504ga3vj.jpg"
imgArray[1] = "http://files.jb51.net/file_images/article/201211/771f735ctw1dnw5gv6dmcj.jpg"
imgArray[2] = "http://files.jb51.net/file_images/article/201211/5d5e9605gw1dnw4o6uk3gj.jpg"
imgArray[3] = "http://files.jb51.net/file_images/article/201211/6d9cb0b8jw1dnw5m0y5yrj.jpg"
imgArray[4] = "http://files.jb51.net/file_images/article/201211/62dae985gw1dnzc4mwvm5j.jpg"
imgArray[5] = "http://files.jb51.net/file_images/article/201211/8d95fb4cgw1dnzec2c6cdj.jpg"
imgArray[6] = "http://files.jb51.net/file_images/article/201211/872bccc8jw1dnzch2aqtkj.jpg"
imgArray[7] = "http://files.jb51.net/file_images/article/201211/5b104465tw1dnzdlozp6tj.jpg"
imgArray[8] = "http://files.jb51.net/file_images/article/201211/6de170f6jw1dnzl7jbzidj.jpg"
imgArray[9] = "http://files.jb51.net/file_images/article/201211/6a93dbfbgw1dnzeiu1draj.jpg"
imgArray[10] = "http://files.jb51.net/file_images/article/201211/6ea59a74jw1dnzm0wbf7vj.jpg"
imgArray[11] = "http://files.jb51.net/file_images/article/201211/48bf076ejw1dnzexjhl6dj.jpg"
imgArray[12] = "http://files.jb51.net/file_images/article/201211/6da7993fjw1dnvsnesrutj.jpg"
imgArray[13] = "http://files.jb51.net/file_images/article/201211/75914d3fgw1dnzlgn33njj.jpg"
imgArray[14] = "http://files.jb51.net/file_images/article/201211/6a8dea72gw1dnzlwnfju0j.jpg"
imgArray[15] = "http://files.jb51.net/file_images/article/201211/696387aagw1dnzqd829yyj.jpg"
//初始化
loadImg()
//主会场
window.onscroll = fun_scroll
//滚动方法
function fun_scroll() {
//body的高度
var topAll = (browser == "Firefox") ? document.documentElement.scrollHeight : document.body.scrollHeight
//卷上去的高度
var top_top = document.body.scrollTop || document.documentElement.scrollTop
//回到顶部按钮操作
if (top_top >showTopButtonHeight)
toTop.style.display = "block"
else
toTop.style.display = "none"
//控制滚动条次数以及判断是否到达底部
if (reset == 0) {
var topAll = (browser == "Firefox") ? document.documentElement.scrollHeight : document.body.scrollHeight//body的高度
var top_top = document.body.scrollTop || document.documentElement.scrollTop//卷上去的高度
var result = topAll - top_top
if (result <surplusHeight) {
setTimeout(loadImg, 1000)
reset = 1
}
} else {
setTimeout(function () { reset = 0}, 1000)
}
}
//加载图片
function loadImg() {
loading.style.display = "none"
for (var i = 0i <bigDivCounti++) {
div1.appendChild(addDiv())
div2.appendChild(addDiv())
div3.appendChild(addDiv())
div4.appendChild(addDiv())
}
setTimeout(function () {
var hh = (browser == "Firefox") ? document.documentElement.scrollHeight : document.body.scrollHeight
loading.style.top = hh + "px"
loading.style.display = "block"
}, 1000)
}
//声明一个包含img和title的div
function addDiv() {
//数组下标的随机值
var ran = Math.round(Math.random() * (imgArray.length - 1))
//title层
var small_div = document.createElement("div")
small_div.innerHTML = textArray[ran]
//内部img
var img = document.createElement("img")
img.alt = ""
img.src = imgArray[ran]
img.style.width = imgWidth
//包含img的层
var div = document.createElement("div")
div.className = "content"
div.appendChild(img)
div.appendChild(small_div)
return div
}
//通过id得到对象
function $(id) {
return document.getElementById(id)
}
//得到浏览器的名称
function getBrowser() {
var OsObject = ""
if (navigator.userAgent.indexOf("MSIE") >0) {
return "MSIE"
}
if (isFirefox = navigator.userAgent.indexOf("Firefox") >0) {
return "Firefox"
}
if (isSafari = navigator.userAgent.indexOf("Safari") >0) {
return "Safari"
}
if (isCamino = navigator.userAgent.indexOf("Camino") >0) {
return "Camino"
}
if (isMozilla = navigator.userAgent.indexOf("Gecko/") >0) {
return "Gecko"
}
}
//回到顶部
toTop.onclick = function () {
var count = 500//每次的距离
var speed = 200//速度
var timer = setInterval(function () {
var top_top = document.body.scrollTop || document.documentElement.scrollTop
var tt = top_top - count
tt = (tt <300) ? 0 : tt
if (top_top >0)
window.scrollTo(tt, tt)
else
clearInterval(timer)
}, speed)
}
}
</script>
</head>
<body>
<h1 id="h1">I like TRY</h1>
<div id="all" class="all">
<div id="one" class="number">
</div>
<div id="two" class="number">
</div>
<div id="three" class="number">
</div>
<div id="four" class="number">
</div>
</div>
<div id="loading" class="loading">
<img src="http://files.jb51.net/file_images/article/201211/200803131036175436.gif" />
</div>
<div id="toTop"><span>△回顶部</span></div>
</body>
</html>
带阴影的时间:<html>
<head>
<style type="text/css">
<!--
.time{
font-family : Comic Sans Ms
font-size : 14pt
font-weight : bold
color: #00008D
}
-->
</style>
<style type="text/css">
<!--
.time{
font-family : Comic Sans Ms
font-size : 14pt
font-weight : bold
color: #00008D
}
-->
</style>
</head>
<script Language="JavaScript">
<!-- Hiding
var ctimer
function init(){
if (document.all){
tim2.style.left=tim1.style.posLeft
tim2.style.top=tim1.style.posTop+tim1.offsetHeight-6
settimes()
}
}
function settimes(){
var time= new Date()
hours= time.getHours()
mins= time.getMinutes()
secs= time.getSeconds()
if (hours<10)
hours="0"+hours
if(mins<10)
mins="0"+mins
if (secs<10)
secs="0"+secs
tim1.innerHTML=hours+":"+mins+":"+secs
tim2.innerHTML=hours+":"+mins+":"+secs
ctimer=setTimeout('settimes()',960)
}
// -->
</script>
<body onLoad="init()">
<div Id="tim1" Style="position:absolutewidth:10height:10top:10left:50"
class="time"></div><div Id="tim2"
Style="position:absolutefilter:flipv() alpha(opacity=20)font-style:italic"
class="time"></div>
</body>
<script Language="JavaScript">
<!-- Hiding
var ctimer
function init(){
if (document.all){
tim2.style.left=tim1.style.posLeft
tim2.style.top=tim1.style.posTop+tim1.offsetHeight-6
settimes()
}
}
function settimes(){
var time= new Date()
hours= time.getHours()
mins= time.getMinutes()
secs= time.getSeconds()
if (hours<10)
hours="0"+hours
if(mins<10)
mins="0"+mins
if (secs<10)
secs="0"+secs
tim1.innerHTML=hours+":"+mins+":"+secs
tim2.innerHTML=hours+":"+mins+":"+secs
ctimer=setTimeout('settimes()',960)
}
// -->
</script>
</html>
多级关联菜单 这个你自己做下小的改动 没有错误的代码
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
var arrItems1 = new Array()
var arrItemsGrp1 = new Array()
arrItems1[3] = "Truck"
arrItemsGrp1[3] = 1
arrItems1[4] = "Train"
arrItemsGrp1[4] = 1
arrItems1[5] = "Car"
arrItemsGrp1[5] = 1
arrItems1[6] = "Boat"
arrItemsGrp1[6] = 2
arrItems1[7] = "Submarine"
arrItemsGrp1[7] = 2
arrItems1[0] = "Planes"
arrItemsGrp1[0] = 3
arrItems1[1] = "Ultralight"
arrItemsGrp1[1] = 3
arrItems1[2] = "Glider"
arrItemsGrp1[2] = 3
var arrItems2 = new Array()
var arrItemsGrp2 = new Array()
arrItems2[21] = "747"
arrItemsGrp2[21] = 0
arrItems2[22] = "Cessna"
arrItemsGrp2[22] = 0
arrItems2[31] = "Kolb Flyer"
arrItemsGrp2[31] = 1
arrItems2[34] = "Kitfox"
arrItemsGrp2[34] = 1
arrItems2[35] = "Schwietzer Glider"
arrItemsGrp2[35] = 2
arrItems2[99] = "Chevy Malibu"
arrItemsGrp2[99] = 5
arrItems2[100] = "Lincoln LS"
arrItemsGrp2[100] = 5
arrItems2[57] = "BMW Z3"
arrItemsGrp2[57] = 5
arrItems2[101] = "F-150"
arrItemsGrp2[101] = 3
arrItems2[102] = "Tahoe"
arrItemsGrp2[102] = 3
arrItems2[103] = "Freight Train"
arrItemsGrp2[103] = 4
arrItems2[104] = "Passenger Train"
arrItemsGrp2[104] = 4
arrItems2[105] = "Oil Tanker"
arrItemsGrp2[105] = 6
arrItems2[106] = "Fishing Boat"
arrItemsGrp2[106] = 6
arrItems2[200] = "Los Angelas Class"
arrItemsGrp2[200] = 7
arrItems2[201] = "Kilo Class"
arrItemsGrp2[201] = 7
arrItems2[203] = "Seawolf Class"
arrItemsGrp2[203] = 7
function selectChange(control, controlToPopulate, ItemArray, GroupArray)
{
var myEle
var x
// Empty the second drop down box of any choices
for (var q=controlToPopulate.options.lengthq>=0q--) controlToPopulate.options[q]=null
if (control.name == "firstChoice") {
// Empty the third drop down box of any choices
for (var q=myChoices.thirdChoice.options.lengthq>=0q--) myChoices.thirdChoice.options[q] = null
}
// ADD Default Choice - in case there are no values
myEle = document.createElement("option")
myEle.value = 0
myEle.text = "[SELECT]"
controlToPopulate.add(myEle)
for ( x = 0 x <ItemArray.length x++ )
{
if ( GroupArray[x] == control.value )
{
myEle = document.createElement("option")
myEle.value = x
myEle.text = ItemArray[x]
controlToPopulate.add(myEle)
}
}
}
// End -->
</script>
<form name=myChoices>
<table align="center">
<tr>
<td>
<SELECT id=firstChoice name=firstChoice onchange="selectChange(this, myChoices.secondChoice, arrItems1, arrItemsGrp1)">
<option value=0 SELECTED>[SELECT]</option>
<option value=1>Land</option>
<option value=2>Sea</option>
<option value=3>Air</option>
</SELECT>
</TD><TD>
<SELECT id=secondChoice name=secondChoice onchange="selectChange(this, myChoices.thirdChoice, arrItems2, arrItemsGrp2)">
</SELECT>
<SELECT id=thirdChoice name=thirdChoice>
</SELECT>
</TD>
</TR>
</TABLE>
</form>
希望对你有所帮助