前端开发中常用到的js特效有哪些

JavaScript017

前端开发中常用到的js特效有哪些,第1张

HTML5 DOM 选择器

// 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

JS特效就是网页中实现的特殊效果或者特殊的功能的一种技术,是用网页脚本(javascript)来编写制作动态特殊效果。

比如图片切换,渐变等等,它为网页活跃了网页的气氛,有时候会起到一定的亲切力。

JavaScript 是根据 "ECMAScript"标准制定的网页脚本语言。这个标准由 ECMA 组织发展和维护。ECMA-262 是正式的 JavaScript 标准。

扩展资料:

能够具有交互性,能够包含更多活跃的元素,就有必要在网页中嵌入其它的技术。如:Javascript、VBScript、Document Object Model(DOM,文档对象模型)、Layers和 Cascading Style Sheets(CSS,层叠样式表)。

JavaScript 使网页增加互动性。JavaScript 使有规律地重复的HTML文段简化,减少下载时间。JavaScript 能及时响应用户的操作,对提交表单做即时的检查,无需浪费时间交由 CGI 验证。JavaScript 的特点是无穷无尽的,只要你有创意。

<script>

function CoolMenuControl(){

// 常规变量 this lastScrollX= this lastScrollY= this lastScrollW= this lastScrollH= this td_X= this td_Y= this td_W= this td_H= this td= this mouseon= this current=null this _namethis table_namethis menudiv_namethis menutable_namethis ml= this menuarray=new Array()this speedthis href=""

// 菜单项目 function menuitem(type value url target){ this type=type this value=value this url=url this target=target }

// 插入菜单 this insertmenu=function(type value url target){  this menuarray[this menuarray length]=new menuitem(type value url target) }

// 程序初试化 this init=function(name bdc bgc speed Alpha){  var in="" var cellcount= var lastcellcount= this _name=name+"" this table_name=name+"table" this menudiv_name=name+"menudiv" this menutable_name=name+"menutable" this speed=speed

for (i= i<this menuarray lengthi++)  {  if (this menuarray[i] type==" ") cellcount=cellcount+  if (this menuarray[i] type==" " || this menuarray[i] type==" ") {cellcount= }  if (lastcellcount<cellcount) {lastcellcount++}    }

//alert(cellcount)

stylecode="cursor:handfilter:Alpha(style= opacity="+Alpha+")background color:"+bgc

suspendcode="<DIV id="+this _name+" style= POSITION:absoluteonclick= "+name+" doClick() >"  +"<table id="+this table_name+" border= width= cellspacing= style= border collapse: collapse bordercolor= "+bdc+" >"  +"<tr><td height= style= "+stylecode+" ></td></tr></table></div>"document write(suspendcode)var fcell=true for (i= i<this menuarray lengthi++) {  switch(this menuarray[i] type)  {  case " ":  t=cellcount*  if (t<= )   {  in+= <tr><td colspan= class=ht onmouseover= +name+ href=" +this menuarray[i] url+ +this menuarray[i] target+ " >+this menuarray[i] value  }  else  {  in+= <tr><td colspan= +t+ class=ht onmouseover= +name+ href=" +this menuarray[i] url+ +this menuarray[i] target+ " >+this menuarray[i] value  }  fcell=true  break case " ":  t=(cellcount )*  if (t<= )   {  in+= <tr><td width= ><td onmouseover= +name+ href=" +this menuarray[i] url+ +this menuarray[i] target+ " >+this menuarray[i] value  }  else  {  in+= <tr><td width= ><td colspan= +t+ onmouseover= +name+ href=" +this menuarray[i] url+ +this menuarray[i] target+ " >+this menuarray[i] value  }  fcell=true  break   case " ":  if (fcell)  {  in+= <tr><td width= ><td onmouseover= +name+ href=" +this menuarray[i] url+ +this menuarray[i] target+ " >+this menuarray[i] value fcell=false  }  else  {  in+= <td width= ><td onmouseover= +name+ href=" +this menuarray[i] url+ +this menuarray[i] target+ " >+this menuarray[i] value }  break } } in= <div id= +this menudiv_name+ onmousemove=" +name+ doOver()"> + <table id= +this menutable_name+ border= cellpadding=" " class="menu" cellspacing=" "> +in  + </table></div>//alert(in) document write(in)

this lastScrollX= this lastScrollY= this posXY(eval(this menutable_name) cells[ ]) this td_W=eval(this menutable_name) cells[ ] scrollWidth+   this td_H=eval(this menutable_name) cells[ ] scrollHeight setInterval(name+" scrollback()" ) }

// 单击超连接 this doClick=function(){  //alert(this url)  var url=this href split(" ")  //alert(url[ ])  //alert(url[ ]) if (url[ ]=="") return

if (url[ ]=="_blank")  {window open(url[ ])}  else  {location href=url[ ]} }

// 滑动处理 this scrollback=function(){ diffX=this td_X diffY=this td_Y diffW=this td_W diffH=this td_H percentX=this speed*(diffX this lastScrollX)percentY=this speed*(diffY this lastScrollY)percentW=this speed*(diffW this lastScrollW)percentH=this speed*(diffH this lastScrollH)

if(percentX>)percentX=Math ceil(percentX)else percentX=Math floor(percentX)if(percentY>)percentY=Math ceil(percentY)else percentY=Math floor(percentY)if(percentW>)percentW=Math ceil(percentW)else percentW=Math floor(percentW)if(percentH>)percentH=Math ceil(percentH)else percentH=Math floor(percentH)

eval(this _name) style pixelTop+=percentYeval(this _name) style pixelLeft+=percentXeval(this table_name) style pixelWidth+=percentWeval(this table_name) style pixelHeight+=percentH

this lastScrollX=this lastScrollX+percentXthis lastScrollY=this lastScrollY+percentYthis lastScrollW=this lastScrollW+percentWthis lastScrollH=this lastScrollH+percentH}

// 滑出 this doOver=function() {  if (event srcElement tagName=="TD") {  if (event srcElement innerText length== || event srcElement innerText=="|") return  this posXY(event srcElement)  this td_W=event srcElement scrollWidth+    this td_H=event srcElement scrollHeight  } }

// 绝对定位 this posXY=function(obj){  _left=obj offsetLeft  _top=obj offsetTop  vParent = obj offsetParent   while (vParent tagName toUpperCase() != "BODY")  {  _left += vParent offsetLeft _top += vParent offsetTop vParent = vParent offsetParent }    this td_X=_left  this td_Y=_top }

// 关于 this about=function(){ alert("OK") }

} </script>

<head><meta equiv="Content Language" content="zh cn"><style>b{color=# cursor:hand} menu { font family:Arialcursor:Defaultfont size: pxborder: px # solidborder collapse: collapsefilter:progid:DXImageTransform Microsoft Gradient(gradienttype= startcolorstr=#ffffff endcolorstr=#dddddd)  progid:DXImageTransform Microsoft Shadow(direction= color=#cccccc strength= )} ht{ font weight:bold } </style><! 第一步 实体化X Menu类  用法:  var <实体变量>new CoolMenuControl() ><script language="javascript">var CoolMenu =new CoolMenuControl() var about=new Array() about[ ]="关于X Menu菜单nnAuthor:PuterJamnCopyright n转载请通知本人" about[ ]="关于作者nn"这家伙很懒 什么也没留下!!"

</script></head><body><! 第二步 建立菜单项目    用法:  <实体变量>insertmenu(类型 Html代码 链接网址 目标)   类型 0代表菜单标题 1代表树型菜单子项目 2代表横向菜单子项目   Html代码 显示在菜单上的Html代码  链接网址 不用多说了 网址或Javascript脚本  目标 默认为空 既不在本页打开 "_blank"代表在新的页面打开 例如:   CoolMenu insertmenu(" " "<img src=// blueidea /img/icon/arrow gif>新浪网" " "_blank")   ><script>CoolMenu insertmenu(" " "本站首页" "" "") CoolMenu insertmenu(" " "新闻中心" " "_blank") CoolMenu insertmenu(" " "文章中心" " "_blank") CoolMenu insertmenu(" " "图片欣赏" " "_blank") CoolMenu insertmenu(" " "软件下载" " "_blank") CoolMenu insertmenu(" " "娱乐欣赏" " "_blank") </script>

lishixinzhi/Article/program/Java/JSP/201311/19958