这些常用的H5代码你知道吗

1、返回上一页
第一次在手机端用到返回上一页的时候,只写了window.history.go(-1);这一句。
但是只在安卓手机有效果,兼容苹果手机需要在跳转代码后加上return false;这句。
跳转后刷新页面加上self.location.reload();这句。

window.history.go(-1); //返回上一页
return false; //兼容ios系统
self.location.reload(); //ios刷新页面

2、微信浏览器禁止页面下拉
addEventListener()方法向指定元素添加事件句柄。
preventDefault()方法阻止元素发生默认的行为。

document.addEventListener('touchmove', function(e) {
  e.preventDefault();
}, {
  passive: false
});
document.oncontextmenu = function(e) { //或者return false;
  e.preventDefault();
};

3、媒体查询
方向:横屏/竖屏
orientation:portrait | landscape
portrait:指定输出设备中的页面可见区域高度大于或等于宽度
landscape: 除portrait值情况外,都是landscape

@media screen and (max-width: 320px){ } //宽度
@media only screen and (orientation: landscape) { } //判断横竖屏

4、上传图片显示
将上传的图片显示出来,做后台管理系统的时候有可能会用到。

<input type="file" name="image" onchange="show(this)">
<img id="img" src="" style="display: none;"/>
// JS代码
function show(file){  
  var reader = new FileReader();  // 实例化一个FileReader对象,用于读取文件
  var img = document.getElementById('img');   // 获取要显示图片的标签  
  //读取File对象的数据
  reader.onload = function(evt){
    img.style.display = 'block';
    img.src = evt.target.result;
  }
  reader.readAsDataURL(file.files[0]);
}

5、长按事件

$(".btn").on({  
  touchstart: function(e) { 
    // 长按事件触发  
    timeOutEvent = setTimeout(function() {  
      timeOutEvent = 0;  
      location.href='www.baidu.com'; //跳转链接
    }, 400);    
  },  
  touchmove: function() {  
    clearTimeout(timeOutEvent);  
    timeOutEvent = 0;  
  },  
  touchend: function() {  
    clearTimeout(timeOutEvent);  
    if (timeOutEvent != 0) {  
      alert('长按开启');  
    }  
    return false;  
  }  
})

6、根据页面高度调整样式

var height = $(window).height();
if(height>625){
  $('.box').css("margin-top", "10px");
}

7、清除在浏览器上搜索框中的叉号

.search::-webkit-search-cancel-button{display: none;}
.search[type=search]::-ms-clear{display: none;}

8、判断安卓和ios
做H5页面时,安卓和ios在显示上还是有些区别,所以有的时候我会根据不同的手机系统去做适配,写不同的样式。

var u = navigator.userAgent, app = navigator.appVersion;
//android
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1; 
//ios
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); 
if(isAndroid){ }
else{ }

公众号原文链接

《这些常用的H5代码你知道吗》

    原文作者:老张的前端笔记
    原文地址: https://segmentfault.com/a/1190000020057408
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞