前端开发笔记

1,页面做媒体查询需添加head头

<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no"/>
//移动端加上这个标签才是真正的自适应复制代码

<meta content="yes" name="apple-mobile-web-app-capable">//IOS中safari允许全屏浏览复制代码

<meta content="black" name="apple-mobile-web-app-status-bar-style">
//IOS中Safari顶端状态条样式复制代码

<meta content="telephone=no" name="format-detection"> //忽略将数字变为电话号复制代码

<meta content="email=no" name="format-detection"> //忽略识别email复制代码


2,监听视频是否加载完成 ,禁止选择文本 ,禁止长按链接与图片弹出菜单 去除A连接input标签,点击出现自带的阴影样式屏蔽阴影:

videoElem.addEventListener('canplaythrough',function(){});//监听视频是否加载完成复制代码

2.1禁止选择文本和默认的菜单事件:

Html,body{
    -webkit-user-select: none; user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    -webkit-user-select: none;
    user-select: none;
    -khtml-user-select: none;
}复制代码

pointer-events: none;//禁用鼠标:复制代码
ime-mode:disabled;//禁用输入法:复制代码
-webkit-touch-callout:none;//禁用系统默认菜单:复制代码
pointer-events: none;//禁用触发鼠标或者触屏事件:复制代码
selection { background: #e2eae2; }//自定义文本选择:复制代码
-webkit-touch-callout:none;//禁用ios弹出各种操作窗口复制代码

2.2,禁止长按链接与图片弹出菜单

1,图片必须是背景图,

2,css禁止:

*{
  margin: 0;
  padding: 0;
  - moz-user-select: -moz-none;
  -moz-user-select: none;
  -o-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
  user-select: none;
  -webkit-touch-callout: none;
}复制代码

3,Js禁止

window.ontouchstart = function (e) {
    e.preventDefault();
};复制代码

2.3去除a标签input标签,点击出现自带的阴影样式

设置input标签不能编辑设置属性:readOnly="true"

outline:none;去掉input标签的边框

a,input{ -webkit-tap-highlight-color:rgba(0,0,0,0); } 

Textarea固定宽高resize:none; 

滚动条卡顿在body上加css属性 -webkit-overflow-scrolling: touch;   

2.4屏蔽标签默认阴影:

-webkit-appearance:none;   复制代码

可以同时屏蔽输入框怪异的内阴影,解决iOS下无法修改按钮样式,测试还发现一个小问题就是,加了上面的属性后,iOS下默认还是带有圆角的,不过可以使用 border-radius属性修改。

2.5渐变透明背景

background:-moz-linear-gradient(top,#70D4F5,#E5F4FB);//火狐background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#70D4F5), to(#E5F4FB)); /* Safari 4-5, Chrome 1-9*/background: -webkit-linear-gradient(top, #70D4F5, #E5F4FB); //Safari5.1 Chrome 10+复制代码

两块背景色

.bg{width:100%;height:100%;position: fixed;background-size: 100%;background-image:linear-gradient(to top,red 0%,red 49%,yellow 50%,yellow 100%) ;}background: -webkit-gradient(linear, left top, left bottom, from(darkGray), to(#7A7A7A));复制代码

3,禁止屏幕滑动

$(document).ready(function(e) {function stopScrolling( touchEvent ) {touchEvent.preventDefault();touchEvent.stopPropagation();}
//注释此句会导致click事件和选择按钮点击无效复制代码

document.addEventListener( 'touchstart' , stopScrolling , false );

document.addEventListener( 'touchmove' , stopScrolling , false );

4,旋转动效

.right_top{position: absolute;width: 14%;right: 3%;top: 44%;border: none;}.center{position: absolute;width: 18%;right: 9%;top: 49%;border: none;}.right_top,.center{animation: roll 3s linear 0s;-webkit-animation: roll 3s linear 0s;animation-iteration-count: infinite;-webkit-animation-iteration-count: infinite;animation-direction: normal;-webkit-animation-direction: normal;animation-fill-mode: both;-webkit-animation-fill-mode: both;-ms-animation-fill-mode: both;-webkit-transform-origin:50% 50%;}@keyframes roll{0% {transform: translateX(0%) translateY(0%) scaleX(1) scaleY(1) rotate(0deg) skewX(0deg) skewY(0deg) ;}100% {transform: translateX(0%) translateY(0%) scaleX(1) scaleY(1) rotate(360deg) skewX(0deg) skewY(0deg) ;}}@-webkit-keyframes roll{0% {-webkit-transform: translateX(0%) translateY(0%) scaleX(1) scaleY(1) rotate(0deg) skewX(0deg) skewY(0deg) ;}100% {-webkit-transform: translateX(0%) translateY(0%) scaleX(1) scaleY(1) rotate(360deg) skewX(0deg) skewY(0deg) ;}}复制代码

4,选中图片radio按钮也会被选上

<input type="radio" value= "lanrentuku" id= "333" name="aaa" ><lable for=”333”>;复制代码

5,视频循环播放

var vList = ['视频地址url1', 'url2', '...']; // 初始化播放列表var vLen = vList.length; // 播放列表的长度var curr = 0; // 当前播放的视频var video = new Video();video.addEventListener('end', play);play();function play(e) {video.src = vList[curr];video.load(); // 如果短的话,可以加载完成之后再播放,监听 canplaythrough 事件即可video.play();curr++;if (curr >= vLen) curr = 0; // 播放完了,重新播放}复制代码

6,HTML中让表单input等文本框为只读不可编辑的方法

方法1: οnfοcus=this.blur() 当鼠标放不上就离开焦点

<input type="text" name="input1" value="中国" onfocus=this.blur()> 复制代码

 方法2:readonly 

 <input type="text" name="input1" value="中国" readonly="true"> 复制代码

 方法3: disabled 

<input type="text" name="input1" value="中国" disabled="true">复制代码

7,去除Android click事件的背景色

-webkit-tap-highlight-color: rgba(0,0,0,0);-webkit-tap-highlight-color: transparent;复制代码

8,验证手机号

function checkMobile(value){var reg = /^0?13|4|5|8\d{8}$/;if (reg.test(value)) {return true;}else{return false;};};复制代码

9,验证邮箱

function checkEmail(s){if (s.length > 100) {return false;};
var regu = "[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?";
var re = new RegExp(regu);复制代码
if (s.search(re) != -1) 
{return true;} 
else {return false;
};
};复制代码

10,页面切换动效

$(window).load(function(){  var body = $("body");  var html = $("html");  var content = $(".container");  var input = $(".info input");  var bigtitle = $(".bigtitle");  input.focus(function(){  content.css({"position":"relative", "overflow":"auto"});  stopPreventEventDefault = true;  });  input.blur(function(){ content.css({"position":"relative", "overflow":"hidden"});  stopPreventEventDefault = false;  });  });复制代码

var bool = true;$(function(){var isH =window.innerHeight;console.log(isH);window.onresize = function(){if(window.innerHeight<isH){$("body").css("height",isH + "px");$(".content").css("height",isH + "px");}}复制代码

$(window).load(function(){$("input").focus(function(){var h=$(window).height()+800;bool=false;$(".form,.ov").css({"position":"relative","overflow-y":"scroll","padding-bottom":"20%","overflow-x":"hidden","height":h});stopPreventEventDefault=false;});$("input").blur(function(){bool=true;$(".form,.ov").css({"position":"relative","overflow":"hidden","padding-bottom":"0%"});stopPreventEventDefault=false;});});});复制代码

11,禁止屏幕滑动

$('html,body').on(touchmove,function(e){e.preventDefault()});复制代码

12,阻止冒泡事件

event.stopPropagation();

13,获取鼠标位置

alert("Current mouse position: " + event.pageX + ", " + event.pageY );
//获取鼠标当前相对于页面的坐标复制代码

14,表单内容如果是必填的,则加红星标识.

$(function(){//如果是必填的,则加红星标识.$("form :input.required").each(function(){   var required = $("<strong class='high'> *</strong>"); //创建元素$(this).parent().append(required); //然后将它追加到文档中});});复制代码

15,去除webkit的滚动条

element::-webkit-scrollbar{display: none;}复制代码

16,去除button在ios上的默认样式

-webkit-appearance: none;border-radius: 0复制代码

17,页面高度渲染错误

document.documentElement.style.height = window.innerHeight + 'px'; 
复制代码

18,叠加区高亮

-webkit-tap-highlight-color:rgba(0,0,0,0); 
复制代码

19,禁掉手机页面的分享

function onBridgeReady(){
  WeixinJSBridge.call('hideOptionMenu');
  }
  if (typeof WeixinJSBridge == "undefined"){
    if( document.addEventListener ){
    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
    }else if (document.attachEvent){
    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
    }
  }else{
  	onBridgeReady();
  }复制代码

20,表单提交滚动

$(window).load(function(){
	var body = $("body");
	var html = $("html");
	var biaodan = $(".biaodan input");
	input.focus(function(){
		biaodan.css({"position":"relative", "overflow":"auto"});
		stopPreventEventDefault = true;
	});
	input.blur(function(){
		biaodan.css({"position":"relative", "overflow":"hidden"});
		stopPreventEventDefault = false;
	});
});复制代码

2为单页面里input标签

<script>window.onresize = function() {document.body.style.height = '568px';document.body.css('overflow-y', 'auto');};</script>复制代码

3重新计算

<script>$(function() {resize();});$(window).load(function(){resize();});function resize() {var sw = $(window).width();var sh = $(window).height();var h = $(".wrapper").height();var r = parseFloat(sw/300, 10);var top = h*(r-1)/2;var left = (sw-300)/2;$(".wrapper").css({"-webkit-transform": "scale("+r+","+r+")",});}</script>复制代码

5单页面表单解决安卓手机出现输入法屏幕被压缩问题

<script>var isH = window.innerHeight;</script><script>$(function(){window.onresize = function(){if(window.innerHeight<isH){$("body").css("height",isH + "px");}}});
</script>复制代码

4晃动动效

.pointer{animation:swing 1.5s linear infinite 0.2s;-webkit-animation:swing 1.5s linear infinite 0.2s;}@keyframes swing {0%, 50%, 56%, 62%, 68%, 75%, 100% { transform: rotate(0deg); }53%, 65% { transform: rotate(20deg); }59%, 72% { transform: rotate(-20deg); }}@-webkit-keyframes swing {0%, 50%, 56%, 62%, 68%, 75%, 100% { -webkit-transform: rotate(0deg); }53%, 65% { -webkit-transform: rotate(20deg); }59%, 72% { -webkit-transform: rotate(-20deg); }}复制代码

21,垂直居中

.content {width: 300px;height: 300px;background: orange;margin: 0 auto; //水平居中position: relative; //脱离文档流top: 50%; //偏移margin-top: -150px;}2.content {width: 300px;height: 300px;background: orange;margin: 0 auto; //水平居中position: relative; //脱离文档流top: 50%; //偏移transform: translateY(-50%);}3 body {display: flex;align-items: center; //定义body的元素垂直居中justify-content: center; //定义body的里的元素水平居中}.content {width: 300px;height: 300px;background: orange;}复制代码

22,设置锚点

//跳同页面
<h2>
<a href="#div1">to div1</a>
<a href="#div2">to div2</a>
<a href="#div3">to div3</a>
</h2>
//写法一
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
//写法二,是a标签可以这样
<a name="div1">div1</a>
<a name="div2">div2</a>
<a name="div3">div3</a>复制代码
//跳到不同页
//index.html页面
<a href="index2.html#div1">问题二的解答</a>
//index2.html页面
<div id="div1">div1</div>复制代码

24,循环遍历

var var42 = "";var a = $("input[name='check4-2']");for (var i = 0; i < a.length; i++) {    if (a[i].checked) {        temp = a[i].value;        var42 += temp;    }}复制代码

25,判断横竖屏

//判断手机横竖屏状态:function hengshuping(){if(window.orientation==180||window.orientation==0){alert("竖屏状态!")}if(window.orientation==90||window.orientation==-90){alert("横屏状态!")}}window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", hengshuping, false);//移动端的浏览器一般都支持window.orientation这个参数,通过这个参数可以判断出手机是处在横屏还是竖屏状态。从而根据实际需求而执行相应的程序。通过添加监听事件onorientationchange,进行执行就可以了。@media screen and (orientation: portrait) { }@media screen and (orientation:landscape) { }复制代码

26,解决屏幕闪白现象

.css {-webkit-transform: translate3d(0, 0, 0);-moz-transform: translate3d(0, 0, 0);-ms-transform: translate3d(0, 0, 0);}复制代码

27,pc和手机端上下滑动事件

​(‘body’).swipeDown(function(e){ alert(‘swipeDown’);//偶尔有效 })​(‘body’).swipeLeft(function(){ alert(‘swipeLeft’);//ok }) $(‘body’).swipeRight(function(){ alert(‘swipeRight’);//ok })//手机端上下滑动先禁掉手机自带的上下滑动事件document.addEventListener('touchmove', function (event) { event.preventDefault(); }, false);复制代码

28,菜单滑出与消失

$(".fan").click(function(){var biaozi=$(this).next().css("display");$(".show").slideUp();if(biaozi=="none")$(this).next().slideDown(500);else$(this).next().slideUp(500);}复制代码

29,闪动光点

.guang_yi{animation:guang 0.5s linear infinite 0.5s;-webkit-animation:guang 1s linear infinite 0.5s;}.guang_er{animation:guang 0.5s linear infinite 0.8s;-webkit-animation:guang 1s linear infinite 0.8s;}.guang_san{animation:guang 0.5s linear infinite 1.1s;-webkit-animation:guang 1s linear infinite 1.1s;}@keyframes guang {0% {opacity: 0;}100% {opacity: 1.0;}}@-webkit-keyframes guang {0% {opacity: 0;}100% {opacity: 1.0;}}复制代码

30,正反交错旋转的圆

.animate7{animation: index1_animate7 2s linear 0s;-webkit-animation: index1_animate7 2s linear 0s;animation-iteration-count: infinite;-webkit-animation-iteration-count: infinite;animation-direction: normal;-webkit-animation-direction: normal;animation-fill-mode: none;-webkit-animation-fill-mode: none;-ms-animation-fill-mode: none;-webkit-transform-origin:50% 50%;}.animate9{animation: index1_animate7 4s linear 0s;-webkit-animation: index1_animate7 4s linear 0s;animation-iteration-count: infinite;-webkit-animation-iteration-count: infinite;animation-direction: normal;-webkit-animation-direction: normal;animation-fill-mode: none;-webkit-animation-fill-mode: none;-ms-animation-fill-mode: none;-webkit-transform-origin:50% 50%;}@keyframes index1_animate7{0%{transform:rotate(0deg);}100% {transform:rotate(360deg);}}@-webkit-keyframes index1_animate7{0%{-webkit-transform:rotate(0deg);}100% {-webkit-transform:rotate(360deg);}}.animate8{animation: index1_animate8 3s linear 0s;-webkit-animation: index1_animate8 3s linear 0s;animation-iteration-count: infinite;-webkit-animation-iteration-count: infinite;animation-direction: normal;-webkit-animation-direction: normal;animation-fill-mode: none;-webkit-animation-fill-mode: none;-ms-animation-fill-mode: none;-webkit-transform-origin:50% 50%;}@keyframes index1_animate8{0%{transform:rotate(0deg);}100% {transform:rotate(-360deg);}}@-webkit-keyframes index1_animate8{0%{-webkit-transform:rotate(0deg);}100% {-webkit-transform:rotate(-360deg);}}复制代码

31,去除div给img附带的下边距

body{margin:0;padding:0;-webkit-text-size-adjust:none;color:#000;}img{border:0;vertical-align:bottom;}复制代码

32,使用对齐文本

$ensp;等于半个中文字符宽度

$emsp;等于一个中文字符宽度

最高心法:通过添加<span style="opacity:0;">填充文字宽度</span>

33,block和inline,inline-block的区别inline-table,list-item可以为div设置前缀图片

Block可以让行内元素转换为块级元素

inline可以让块级元素转换为行内元素,但是不能设置宽度,效果和inline-block类似,但是后者可以设置宽度。

33,弹动动效

.tandong{-webkit-animation:bounce 1s .2s ease both;-moz-animation:bounce 1s .2s ease both;}@-webkit-keyframes bounce{0%,20%,50%,80%,100%{-webkit-transform:translateY(0)}40%{-webkit-transform:translateY(-30px)}60%{-webkit-transform:translateY(-15px)}}@-moz-keyframes bounce{0%,20%,50%,80%,100%{-moz-transform:translateY(0)}40%{-moz-transform:translateY(-30px)}60%{-moz-transform:translateY(-15px)}}复制代码

34,闪动

.scan{-webkit-transform-origin:50% 50%;-o-transform-origin:50% 50%;transform-origin:50% 50%;animation:scanup 1s linear 3 0s;-webkit-animation:scanup 1s linear 3 0s;}@-webkit-keyframes scanup {0%{ opacity:0; }100% { opacity:1; }}@keyframes scanup {0%{ opacity:0; }100% { opacity:1; }}复制代码

35,指纹扫描动画

.scan{

-webkit-transform-origin:50% 50%;

-o-transform-origin:50% 50%;

transform-origin:50% 50%;

animation:scanup 2s linear infinite 0s;

-webkit-animation:scanup 2s linear infinite 0s;

}

@-webkit-keyframes scanup {

0%{ -webkit-transform:translate(0,0) }

100% { -webkit-transform:translate(0,-20%) }

}

@keyframes scanup {

0%{ transform:translate(0,0) }

100% { transform:translate(0,-20%) }

}

36,出现随机一段字符

<script>$(function(){/back home/$(".backHome").click(function(){window.location.href="index_support.html";});function randomStr(num){var chars = "dasfdhsdfgj2346158709fds";var len = chars.length;var str = "";for(i=0;i<num;i++){str+=chars.charAt(Math.floor(Math.random()*len));}return str;}// alert(randomStr(10));$(".message").html(randomStr(10));});// function getfirstpage(){// window.location.href="index_support.html"// }</script>复制代码

37,Edm排版

<tr><td><table></table></td></tr><tr><td><table></table></td></tr><tr><td><table></table></td></tr></table>复制代码

38,自动输入

<script>function focusTxt_en(){marquee_en(1);}function marquee_en(i){var showString= "OceanStor 9000 V100R001C30";var stringLength= showString.length;$(".serch_input").val(showString.substring(0, i));i++;var timeID= setTimeout("marquee_en("+i+")",100);if (i > stringLength){clearTimeout(timeID);}$(".serch_input").blur();//每获取一次焦点就取消一次焦点,防止平板触摸键盘自动弹出}</script><body><input type="text" class="serch_input" onfocus="focusTxt_en()" value="" title="Please enter keywords."></body>复制代码

39,关于对话流的对话框背景铺满问题

40,事件委托 $(selector).live("click",callback)

jQuery的live事件绑定机制非常强大,普通的bind只能在dom元素生成后才能绑定事件,而live则可以在任何时候,即使元素还没有生成时就能绑定事件,

41,解决微信无法播放音乐

function audioAutoPlay(id){ var audio = document.getElementById(id); 
var play = function() {          
document.removeEventListener("WeixinJSBridgeReady", play); 
document.removeEventListener("YixinJSBridgeReady", play); 
audio.play(); 
audio.pause(); 
// document.removeEventListener("touchstart", play, false); }; 
audio.play(); 
audio.pause(); 
//weixin document.addEventListener("WeixinJSBridgeReady", play, false); 
//yixin document.addEventListener('YixinJSBridgeReady', play, false); 
// document.addEventListener("touchstart", play, false); } 
audioAutoPlay('audio1');复制代码

42,关于浏览器的判断

if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/6./i)=="6."){ alert("IE 6"); } else if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/7./i)=="7."){ alert("IE 7"); } else if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/8./i)=="8."){ alert("IE 8"); } else if(navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.match(/9./i)=="9."){ alert("IE 9"); }复制代码

43,判断是pc端还是移动端

function browserRedirect() {var sUserAgent = navigator.userAgent.toLowerCase();var bIsIpad = sUserAgent.match(/ipad/i) == "ipad";var bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";var bIsMidp = sUserAgent.match(/midp/i) == "midp";var bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";var bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";var bIsAndroid = sUserAgent.match(/android/i) == "android";var bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";var bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";document.writeln("您的浏览设备为:");if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {document.writeln("phone");} else {document.writeln("pc");}}browserRedirect();复制代码

43,判断是否是微信浏览器

<script type="text/javascript">function isMicroMessenger(){var result=false;var ua=navigator.userAgent;if(us.indexOf('MicroMessenger')>-1){result=true;}return result;}</script>复制代码

44,取出数组的相同项并由大到小排序

<script>var a=[1,3,1,4,2,3,6,2,6,1,5];var c=[];var zi;var k=0;var len_a=a.length;for(var i=0;i<len_a;i++){for(var j=0;j<len_a;j++){if(a[i]==a[j]&&i!=j){zi=a[i];}}var len_t=c.length;// alert(len_t);if(len_t==0){c[k]=zi;k=k+1;//console.log(c);}else if(len_t>0){var t=c.indexOf(zi);if(t==-1){c[k]=zi;k=k+1;//console.log(c);}}}for(var f=0;f<c.length;f++){for(var r = f + 1;r<c.length;r++){if(c[f]<c[r]){var temp = c[r];c[r] = c[f];c[f] = temp;}}console.log(c);}</script>复制代码

46,iframe里面传值问题

46.1**子页面内容**

// iframe里面的子页面的值传到父页面var data1=a;var data2=fxzi;parent.GetData(data1,data2);//子页面调用父页面的函数//window.parent.sharefun();复制代码

46.2父页面内容

// iframe里面的子页面的值传到父页面
function GetData(data1,data2){// if(data==a)//alert(data1);a=data1;fxzi=data2;// alert(a);// alert(fxzi);sharefun();}复制代码

47,错误SyntaxError illegal character的解决方法

注意:函数调用过程中中英文符号的使用,例如(,或;)

48,让浮动元素填充内容

<div class="clear"></div>1. clear{overflow:auto/hidden;zoom:1;}2. clear:after{content:”dddd”;height:0;visibility:none;clear:both;}3. 添加一个空的p标签然后给p标签设置样式清除浮动复制代码

49,获取链接后面的参数

<script>function getPar(par){//获取当前URLvar local_url = document.location.href;//获取要取得的get参数位置var get = local_url.indexOf(par +"=");if(get == -1){return false;}//截取字符串var get_par = local_url.slice(par.length + get + 1);//判断截取后的字符串是否还有其他get参数var nextPar = get_par.indexOf("&");if(nextPar != -1){get_par = get_par.slice(0, nextPar);}return get_par;}alert(getPar("p"));</script>复制代码

50,stop()函数参数问题

stop(true)等价于stop(true,false): 停止被选元素的所有加入队列的动画。

stop(true,true):停止被选元素的所有加入队列的动画,但允许完成当前动画。

stop()等价于stop(false,false):停止被选元素当前的动画,但允许完成以后队列的所有动画。

stop(false,true):立即结束当前的动画到最终效果,然后完成以后队列的所以动画

51手动开启硬件加速,在你打开或显示一个窗口页面时设置样式里 styles: { top: 0, bottom: 0, hardwareAccelerated: true,//开启硬件加速 scrollIndicator: 'none' }

52,还回上一页

onclick="history.go(-1)"< a href="javascript:history.go(-1)">返回</ a>复制代码

53,文档首字母设置

text-transform:capitalize; 首字母大写 

text-transform:uppercase;所有单词大写 

text-transform:lowercase;所有单词小写

54,禁止触摸移动事件

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);复制代码

55,解决ie8兼容background

filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='....', sizingMethod='scale'); 可以解决ie不识别background-size的属性

56,localStorage与sessionStorage用法

localStorage.setItem('myCat', 'Tom');设置

var cat = localStorage.getItem("myCat");拿取

localStorage.removeItem("myCat");移除

sessionStorage.setItem('can','true');设置值

var can = sessionStorage.getItem('can');获取值

页面关闭值被清除

57,关于input标签获取值问题

var scbn=$("input[name='na"+scan+"']:checked").length;

判断被选中的个数

ti4=parseInt($("input[name=na4]:checked").val());

获取被选中的按钮的value值

$("input[name='na"+i+"']").attr("checked",false);

所有选中重置

58,滚动条,滑动效果

window.onload=function(){var scrollT = $(window).scrollTop();if(scrollT == 0){$(".product").addClass("slide");setTimeout(function(){$(".prodcDiv .rowEvs,.prodcDiv .more").addClass("slide");},800);}$(window).scroll(function(){var scrollT = $(window).scrollTop();if(scrollT > 50){$(".solution").addClass("slide");setTimeout(function(){$(".data,.soluDiv .more").addClass("slide");},800);}});}复制代码

60,禁用页面的右键菜单

<script>$(document).ready(function(){$(document).bind("contextmenu",function(e){return false;});});</script>复制代码

62,判断浏览器类型

<script>// Firefox 2 and aboveif (Misplaced &​.browser.version= "1.8" ){// do something}// Safariif( $.browser.safari ){// do something}// Chromeif( $.browser.chrome){// do something}// Operaif( $.browser.opera){// do something}// IE6 and belowif (Misplaced &​.browser.version <= 6 ){alert("ie6")}// anything above IE6if (Misplaced &​.browser.version6){alert("ie6以上")}});</script>复制代码

63,输入框文字获取和失去焦点

<input type="text" class="text1"/><script>$(document).ready(function() {$("input.text1").val("Enter your search text here.");textFill( $('input.text1') );}); function textFill(input){ //input focus text functionvar originalvalue = input.val();input.focus( function(){if( $.trim(input.val()) == originalvalue ){input.val('');}}).blur( function(){if( $.trim(input.val()) == '' ){input.val(originalvalue);}});}</script>复制代码

64,获取鼠标位置

<script>

    $(document).ready(function () {

        $(document).mousemove(function(e){

            $('#XY').html("X : " + e.pageX + " | Y : " + e.pageY);

        });

    });

</script>
复制代码

65,判断元素是否存在

<script>
    $(document).ready(function() {
        if ($('#XY').length){
            alert('元素存在!')
        }else{
            alert('元素不存在!')
        }
    });
</script>
复制代码

66,点击div也可以跳转

<div style="width:200px;height:40px;background:#eee;cursor:pointer;">
    <a href="http://www.cssrain.cn">home</a>
</div>
<script>
    $(document).ready(function() {
        $("div").click(function(){
            window.location=$(this).find("a").attr("href");
            return false;
        });
    });
</script>
复制代码

67,根据浏览器大小添加不同的样式

<style>​    
body.large{​        
font-size:20px;​    
}​    
body.large a{
​        font-size:20px;​
        color:red;​
    }​
</style>​
</head>​
<body>​
<ul>​
    <li><a title="百 度" target="_blank" href="http://www.baidu.com/index.php?tn=monline_5_dg">百 度</a></li>​   
    <li><a title="Google" target="_blank" href="http://i.firefoxchina.cn/parts/google_rdr.html">Google</a></li>​    
    <li><a title="新浪" target="_blank" href="http://www.sina.com.cn/">新浪</a></li>​
</ul>
​​​<script>​    
$(document).ready(function() {​
        function checkWindowSize() {​
            if ( $(window).width() > 900 ) {​
                $('body').addClass('large');​
            }else{
​                $('body').removeClass('large');
​            }
​        }​
        $(window).resize(checkWindowSize);​
    });​
</script>复制代码

68,设置div在屏幕中央

<style>​​​    
#XY{​
        width:460px;​
        height:300px;​
        background:#aaa;
​    }
​</style>​
</head>​
<body>​
<div id="XY">
</div>​​​
<script>​
    $(document).ready(function() {​
        jQuery.fn.center = function () {​
            this.css("position","absolute");​
            this.css("top", ( $(window).height() - this.height() )/ 2+$(window).scrollTop() + "px");​
            this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px");​
            return this;
​        }​
        //use​        
        $("#XY").center();
​    });​​​
</script>复制代码

69,关闭所有动画效果

<style>
​    #XY{​
        width:40px;​
        height:100px;​
        background:#aaa;
​    }​
</style>
​​​<button id="XY1" class="box">开始动画</button>
​<button id="XY2" class="box">关闭动画</button>
​<button id="XY3" class="box">开启动画</button>
​<div id="XY" class="box"></div>
​​​<script>​
    $(document).ready(function() {
​        $("#XY1").click(function(){​
            animateIt();
​        });
​        $("#XY2").click(function(){​
            jQuery.fx.off = true;
​        });​
        $("#XY3").click(function(){​
            jQuery.fx.off = false;
​        });​
    });
​​​    function animateIt() {​
        $("#XY").slideToggle("slow");
​    }
​</script>复制代码

70,检测鼠标的右键和左键

<style>
    #XY{
        width:40px;
        height:100px;
        background:#aaa;
    }
</style>
<div id="XY" class="box"></div>
<script>
    $(document).ready(function() {
        $("#XY").mousedown(function(e){
            alert(e.which)  // 1 = 鼠标左键 ; 2 = 鼠标中键; 3 = 鼠标右键
        })
    });
</script>
复制代码

71,回车提交表单

<style>
    #XY{
        width:40px;
        height:100px;
        background:#aaa;
    }
</style>
<input type="input" />
<script>
    $(document).ready(function() {
        $("input").keyup(function(e){
            if(e.which=="13"){
                alert("回车提交!")
            }
        })
    });
</script>
复制代码

72,设置全局Ajax参数

<style>​
    #load{​
        display:none;​
    }​
</style>​​​
<div id="load">加载中...</div>​
<input type="button" id="send1" value="ajax"/>
​<div id="resText1"></div>
​​​<script>​
    $(document).ready(function() {
​        $('#send1').click(function() {
​            $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=car&tagmode=any&format=json&jsoncallback=?",function(data){
​                        $("#resText1").empty();​
                        $.each(data.items, function( i,item ){​
                            $("<img/> ").attr("src", item.media.m ).appendTo("#resText1");
​                            if ( i == 3 ) {​
                                return false;​
                            }​
                        });​
                    }​
            );
​        });
​​​        $.ajaxPrefilter(function( options ) {​
            options.global = true;​
        });​
        $("#load").ajaxStart(function(){​
            showLoading(); //显示loading​
            disableButtons(); //禁用按钮​
        });
​        $("#load").ajaxComplete(function(){​
            hideLoading(); //隐藏loading​
            enableButtons(); //启用按钮​
        });​​​
    });
​​​    function showLoading(){​
        $("#load").show();​
    }​
    function hideLoading(){
​        $("#load").hide();​
    }​
    function disableButtons(){​
        $("#send1").attr("disabled","disabled");​
    }​
    function enableButtons(){
​        $("#send1").removeAttr("disabled");
​    }​​​​​
</script>复制代码

73,获取选中的下拉框

<input type="button" id="send1" value="get"/>
<select id="someElement">
    <option>一班</option>
    <option>二班</option>
    <option>三班</option>
</select>
<script>
    function getObj(){
        var $obj = $('#someElement').find('option:selected');
        alert( $obj.val() );
    }
</script>
复制代码

74,切换复选框

<button>toggle</button>
​<input type="checkbox" value="1" />篮球​
<input type="checkbox" value="2" />足球​
<input type="checkbox" value="3" />羽毛球
​​​<script>​
    var tog = false;
​    $('button').click(function(){​
        $("input[type=checkbox]").attr("checked",!tog);
​        tog = !tog;
​    });
​​​</script>复制代码

75,使用siblings()来选择同辈元素

<style>​
    li.active{
​        font-size:20px;​
        color:red;​
    }​
</style>​
<ul id="nav">​
    <li>Google</li>​
    <li>百 度</li>​
    <li>新浪</li>​
</ul>​
<script>​
    /* 不这样做
​     $('#nav li').click(function(){​
     $('#nav li').removeClass('active');​
     $(this).addClass('active');​
     });​
     */​
    //替代做法是​
    $('#nav li').click(function(){​
        $(this).addClass('active')​
                .siblings().removeClass('active');​
    });​
</script>复制代码

76,检查某个元素是否包含某个类或是元素

<style type="text/css">​
    body {​
        margin: 10px auto;
​        width: 570px;​
        font: 75%/120% Arial, Helvetica, sans-serif;
​        color: #999999;​
    }​
    a {​
        color:#333399;​
    }​
    a:hover {
​        text-decoration: none;​
    }​
    a.pdf {​
        background: url(img/file-red.gif) no-repeat;
​        padding-left: 16px;​
    }​
    a.zip {​
        background: url(img/file-orange.gif) no-repeat;​
        padding-left: 16px;​
    }​
    a.psd {
​        background: url(img/file-blue.gif) no-repeat;​
        padding-left: 16px;
​    }​
</style>​
<script src="../../scripts/jquery.js" type="text/javascript"></script>​​​
<p><a href="http://www.webdesignerwall.com/file/wdw-logo.pdf">PDF file</a>(wdw-logo.pdf)</p>
​<p><a href="http://www.webdesignerwall.com/file/wdw-logo.psd">PSD file</a>(wdw-logo.psd)</p>​
<p><a href="http://www.webdesignerwall.com/file/wdw-logo.zip">Zip file</a>(wdw-logo.zip)</p>​​​
<script type="text/javascript">
​    $(document).ready(function(){
​        $("a[href$='pdf']").addClass("pdf");​
        $("a[href$='zip']").addClass("zip");​
        $("a[href$='psd']").addClass("psd");
​    });​
</script>复制代码

77,在一段时间之后自动隐藏或关闭元素

<p><button>Run</button></p>
​<div class="first">Test</div>​​​
<script type="text/javascript">​
    $(document).ready(function(){​
        $("button").click(function() {
​            $("div").slideUp(300).delay(3000).fadeIn(400);​
        });​
        /*​
         //这是1.3.2中我们使用setTimeout来实现的方式​
         setTimeout(function() {​
         $('div').fadeIn(400)​
         }, 3000);​
         */​
        //而在1.4之后的版本可以使用delay()这一功能来实现的方式​
        //$("div").slideUp(300).delay(3000).fadeIn(400);​
    });
​</script>复制代码

78,boder-radius爱心

.heart{    position: relative;    width: 160px;    height: 200px;}.heart:before{    position: absolute;    left: 20px;    width: 80px;    height: 120px;    content: " ";    background: #f00;    -moz-border-radius: 100px;    -webkit-border-radius: 100px;    border-radius: 100px 100px 0 0;    -webkit-transform: rotate(-45deg);}.heart:after{    position: absolute;    left: 48px;    top: 0px;    width: 80px;    height: 120px;    content: " ";    background: #f00;    -moz-border-radius: 100px;    -webkit-border-radius: 100px;    border-radius: 100px 100px 0 0;    -webkit-transform: rotate(45deg);}<div class="heart"></div>复制代码

79,动态绑定事件

<script type="text/javascript">$(document).ready(function(){/*// 为table里面的td元素绑定click事件,不管td元素是一直存在还是动态创建的// jQuery 1.4.2之前使用的方式$("table").each(function(){  $("td", this).live("click", function(){    $(this).toggleClass("hover");  });});// jQuery 1.4.2 使用的方式$("table").delegate("td", "click", function(){  $(this).toggleClass("hover");});*/// jQuery 1.7.1使用的方式$("table").on("click","td",function(){$(this).toggleClass("hover");});});</script>复制代码

80,圆角bug

某些Android手机圆角失效

background-clip: padding-box;

81,长按触发事件

1<script>var timeOutEvent=0;$(function(){$(".stage").on({touchstart: function(e){timeOutEvent = setTimeout("longPress()",2000);e.preventDefault();},touchmove: function(){clearTimeout(timeOutEvent);timeOutEvent = 0;},touchend: function(){clearTimeout(timeOutEvent);if(timeOutEvent!=0){alert("你这是点击,不是长按");}return false;}})});function longPress(){timeOutEvent = 0;alert("长按事件触发发");}</script>2$(window).load(function(){q=0;var timer;var timeout = 10;var touchshijian = $("#touch");touchshijian[0].addEventListener("touchstart", function(e) {e.preventDefault();q = 0;timer = setInterval(function() {q = q+1;if(q > timeout) {q=0;window.location.href="indexinner.php";clearInterval(timer);}},100);});touchshijian[0].addEventListener("touchend", function(e) {e.preventDefault();if(q <= timeout) {clearInterval(timer);}});});</script>复制代码

82,animate详解

Animate({width:”100px”},2000,liners,function(){内容})

1width后面的参数非数字必加引号

2回调函数必须是function不能直接是change()不然会在开始时就调用change()

83,解决弹窗

添加一个div层设置透明度为0即可

position: absolute;width:100%;height:100%;top:0;left:0;background: rgba(0,0,0,0);-webkit-touch-callout: none;-webkit-user-select: none;复制代码

84,关于stop()函数参数分析

关于stop()函数参数详解第一个参数设置为true,停止所有动画,为false仅停止当前动画,第二个参数设置为true,所有动画保持完成状态,为false则仅停在被停止的地方

85,发短信打电话

<a href="tel:10086">10086</a>     //点击后直接拨打10086
<a href="mailto:c1586@qq.com?subject=TestObject">c6088@qq.com</a>  //点击后直接给c1586@qq.com发邮件,主题为:TestObject           
<a href="sms:10086?body=message_body">给 10086 发短信</a>          //点击后直接给10086发信息,消息内容默认为message_body   
<a href="geopoint:116.281469,39.866035">我的位置</a> //点击后直接发送自己的位置复制代码

86,禁止浏览器打开,仅在微信浏览器可以打开

<script>var useragent = navigator.userAgent;if (useragent.match(/MicroMessenger/i) != 'MicroMessenger') {// 这里警告框会阻塞当前页面继续加载alert('已禁止本次访问:您必须使用微信内置浏览器访问本页面!');// 以下代码是用javascript强行关闭当前页面var opened = window.open('about:blank', '_self');opened.opener = null;opened.close();}</script> 复制代码

87,判断是否注册,没有调到注册页

function register(url){var f1 = localStorage.getItem("form1");if(f1 == 'true'){window.open(url);}else{window.location.href='register.html?source='+ document.getElementById('source').value;}}复制代码

88,target

e = e || window.event;e.target = e.target || e.srcElement;alert(e.target.nodeName);复制代码

89,解决ie8不能识别indexof问题

if (!Array.prototype.indexOf){Array.prototype.indexOf = function(elt /, from/){var len = this.length >>> 0;var from = Number(arguments[1]) || 0;from = (from < 0)? Math.ceil(from): Math.floor(from);if (from < 0)from += len;for (; from < len; from++){if (from in this &&this[from] === elt)return from;}return -1;};}复制代码

90,ie8浏览器SCRIPT5007: 无法获取未定义或 null 引用的属性“0”

数组最后元素的逗号要去掉

91,解决苹果手机在placeholder里面内容不能换行问题

var placeholder = '第一行文本提示\n第二行文本提示\n第三行文本提示';$('textarea').val(placeholder);$('textarea').focus(function() {if ($(this).val() == placeholder) {$(this).val('');}});$('textarea').blur(function() {if ($(this).val() == '') {$(this).val(placeholder);}});复制代码

92,解决ipad不兼容background-attachment: fixed;

body:before {content: ' ';position: fixed;z-index: -1;top: 0;right: 0;bottom: 0;left: 0;background: url(path/to/image) center 0 no-repeat;background-size: cover;}复制代码

93,兼容禁止屏幕放大缩小

<script type="text/javascript">window.onload=function () {document.addEventListener('touchstart',function (event) {if(event.touches.length>1){event.preventDefault();}})var lastTouchEnd=0;document.addEventListener('touchend',function (event) {var now=(new Date()).getTime();if(now-lastTouchEnd<=300){event.preventDefault();}lastTouchEnd=now;},false)}</script>复制代码

94,解决跨域问题

1, 通过绑定同样的域名,在同级下访问

2, 通过建立代理服务

95,创建帧动画

window.requestAnimFrame = (function(){return window.requestAnimationFrame ||window.webkitRequestAnimationFrame ||window.mozRequestAnimationFrame ||function( callback ){window.setTimeout(callback, 1000 / 60);};})();(function animloop(){requestAnimFrame(animloop);render();})();
复制代码

96,给后端传&特殊字符会被转义

解决办法可以通过escape转义,然后在unescape转义回来传输

97,数组通过关键词排序

students:[
  {name:'jspang',age:32},
  {name:'Panda',age:30},
  {name:'PanPaN',age:21},
  {name:'King',age:45}
]复制代码
//数组对象方法排序:
function sortByKey(array,key){
    return array.sort(function(a,b){
      var x=a[key];
      var y=b[key];
      return ((x<y)?-1:((x>y)?1:0));
   });
}复制代码
sortStudent:function(){
     return sortByKey(this.students,'age');
}复制代码


转载于:https://juejin.im/post/5cd5a01751882569662c1239

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值