祝各位道友念头通达
GitHub Gitee 语雀 打赏

css和js前端技术网站分享,做项目中碰见js各种效果的代码,定位.手势滑动,textare随着内容增加高度自动变化,静态页面传值

>前端 100多种时钟展示: http://www.webhek.com/post/clock-shop.html

>jquery 各种日历插件以及模态框展示特效等: http://www.17sucai.com/

>前端各种图标展示:http://www.fontawesome.com.cn/faicons/

>bootstrap表单快速构造:http://www.bootcss.com/p/bootstrap-form-builder/

 元素,按钮,日历插件,图标等>http://element-cn.eleme.io/#/zh-CN/component/icon;

bootstrap-日历插件>http://www.bootcss.com/p/bootstrap-datetimepicker/

 

js手势滑动代码

//=====================================手机端页面滑动展示效果==========================================================//
    /**
     * 手机端页面滑动显示代码
     */
    function getSelected(){
        var startx, starty;
        //获得角度
        function getAngle(angx, angy) {
          return Math.atan2(angy, angx) * 180 / Math.PI;
        };
        //根据起点终点返回方向 1向上 2向下 3向左 4向右 0未滑动
        function getDirection(startx, starty, endx, endy) {
          var angx = endx - startx;
          var angy = endy - starty;
          var result = 0;

          //如果滑动距离太短
          if (Math.abs(angx) < 2 && Math.abs(angy) < 2) {
              return result;
          }

          var angle = getAngle(angx, angy);
        if (angle >= -135 && angle <= -45) {
            result = 1;
        } else if (angle > 45 && angle < 135) {
            result = 2;
        } else if ((angle >= 135 && angle <= 180)
                || (angle >= -180 && angle < -135)) {
            result = 3;
        } else if (angle >= -45 && angle <= 45) {
            result = 4;
        }

        return result;
    }
    //手指接触屏幕    document是整个窗口,如果是某个元素,可以换成doucument.getElementById();等等,如果是多个元素,可以循环对元素添加监听事件
    document.addEventListener("touchstart", function(e) {
        startx = e.touches[0].pageX;
        starty = e.touches[0].pageY;
    }, false);
    //手指离开屏幕
    document.addEventListener("touchend", function(e) {
        var endx, endy;
        endx = e.changedTouches[0].pageX;
        endy = e.changedTouches[0].pageY;
        var direction = getDirection(startx, starty, endx, endy);
        /*switch (direction) {
             case 0:
                 alert("未滑动!");
                 break;
             case 1:
                 alert("向上!");
                 break;
             case 2:
                 alert("向下!");
                 break;
             case 3:
                 alert("向左!");
                 break;
             case 4:
                 alert("向右!");
                 break;
             default:
         }*/
        if (direction == 3) {
            alert("向左")
        }
        if (direction == 4) {
            alert("向右")
        }
    }, false);
}

 

 

jquery手势滑动代码 ele是选择器 eg:sliding('body') //给body窗体添加滑动事件

var sliding = function (ele) {
            $(ele).on("touchstart", function (e) {
                // 判断默认行为是否可以被禁用
                if (e.cancelable) {
                    // 判断默认行为是否已经被禁用
                    if (!e.defaultPrevented) {
                        e.preventDefault();
                    }
                }
                startX = e.originalEvent.changedTouches[0].pageX,
                    startY = e.originalEvent.changedTouches[0].pageY;
            });
            $(ele).on("touchend", function (e) {
                // 判断默认行为是否可以被禁用
                if (e.cancelable) {
                    // 判断默认行为是否已经被禁用
                    if (!e.defaultPrevented) {
                        e.preventDefault();
                    }
                }
                moveEndX = e.originalEvent.changedTouches[0].pageX,
                    moveEndY = e.originalEvent.changedTouches[0].pageY,
                    X = moveEndX - startX,
                    Y = moveEndY - startY;
                //左滑
                if (X > 0) {
                    alert('左滑');
                }
                //右滑
                else if (X < 0) {
                    alert('右滑');
                }
                //下滑
                else if (Y > 0) {
                    alert('下滑');
                }
                //上滑
                else if (Y < 0) {
                    alert('上滑');
                }
                //单击
                else {
                    alert('单击');
                }
            });
        }

 

 jquery和scroll不冲突滑动

var sliding = function (ele) {
        $(ele).bind('touchstart',function(e){
            startX = e.originalEvent.changedTouches[0].pageX,
            startY = e.originalEvent.changedTouches[0].pageY;
        });
        $(ele).bind('touchmove',function(e){
            //获取滑动屏幕时的X,Y
            endX = e.originalEvent.changedTouches[0].pageX,
            endY = e.originalEvent.changedTouches[0].pageY;
            //获取滑动距离    
            distanceX = endX-startX;
            distanceY = endY-startY;
            //判断滑动方向
            if(Math.abs(distanceX)>Math.abs(distanceY) && distanceX>0){
               console.log('左滑'+count);
                count--;
                if(count<1){
                    count=1;
                    return false;
                }
                getInfo(count);
            }else if(Math.abs(distanceX)>Math.abs(distanceY) && distanceX<0){
                
                 console.log('右滑'+count);
                count++;
                if(count>4){
                    count=4;
                    return false;
                } 
                getInfo(count);
            }else if(Math.abs(distanceX)<Math.abs(distanceY) && distanceY<0){
                console.log('往上滑动');
            }else if(Math.abs(distanceX)<Math.abs(distanceY) && distanceY>0){
                console.log('往下滑动');
            }else{
                console.log('点击未滑动');
            }

        });
    }

 

 

 

js textarea 随着输入,高度自适应代码,独立代码

  
  使用直接在textarea标签加入函数 onfocus=
autoTextarea(this);即可

  /*
* * 文本框根据输入内容自适应高度 * @param {HTMLElement} 输入框元素 * @param {Number} 设置光标与输入框保持的距离(默认0) * @param {Number} 设置最大高度(可选) */ var autoTextarea = function (elem, extra, maxHeight) { change_lable_content(elem); extra = extra || 0; var isFirefox = !!document.getBoxObjectFor || 'mozInnerScreenX' in window, isOpera = !!window.opera && !!window.opera.toString().indexOf('Opera'), addEvent = function (type, callback) { elem.addEventListener ? elem.addEventListener(type, callback, false) : elem.attachEvent('on' + type, callback); }, getStyle = elem.currentStyle ? function (name) { var val = elem.currentStyle[name]; if (name === 'height' && val.search(/px/i) !== 1) { var rect = elem.getBoundingClientRect(); return rect.bottom - rect.top - parseFloat(getStyle('paddingTop')) - parseFloat(getStyle('paddingBottom')) + 'px'; }; return val; } : function (name) { return getComputedStyle(elem, null)[name]; }, minHeight = parseFloat(getStyle('height')); elem.style.resize = 'none'; var change = function () { var scrollTop, height, padding = 0, style = elem.style; if (elem._length === elem.value.length) return; elem._length = elem.value.length; if (!isFirefox && !isOpera) { padding = parseInt(getStyle('paddingTop')) + parseInt(getStyle('paddingBottom')); }; scrollTop = document.body.scrollTop || document.documentElement.scrollTop; elem.style.height = minHeight + 'px'; if (elem.scrollHeight > minHeight) { if (maxHeight && elem.scrollHeight > maxHeight) { height = maxHeight; style.overflowY = 'auto'; } else { height = elem.scrollHeight; style.overflowY = 'hidden'; }; style.height = height + extra + 'px'; // scrollTop += parseInt(style.height) - elem.currHeight; // document.body.scrollTop = scrollTop; // document.documentElement.scrollTop = scrollTop; elem.currHeight = parseInt(style.height); }; }; addEvent('propertychange', change); addEvent('input', change); addEvent('focus', change); change(); };

 

js获取某周的日期范围


//weeks 为0,或是不传值,默认为当前周,如果需要上周的日期 则传值 -1,以此类推,下周传 1 下下周传2

function weeksRange(weeks){ function getWeek() {
this.nowTime = new Date(); this.init = function() { this.dayInWeek = this.nowTime.getDay(); this.dayInWeek == 0 && (this.dayInWeek = 7); this.thsiWeekFirstDay = this.nowTime.getTime() - (this.dayInWeek - 1) * 86400000; this.thisWeekLastDay = this.nowTime.getTime() + (7 - this.dayInWeek) * 86400000; return this; }; this.getWeekType = function(type) { type = ~~type; var firstDay = this.thsiWeekFirstDay + type * 7 * 86400000; var lastDay = this.thisWeekLastDay + type * 7 * 86400000; return this.getWeekHtml(firstDay, lastDay); } this.formateDate = function(time) { var newTime = new Date(time) var year = newTime.getFullYear(); var month = newTime.getMonth() + 1; var day = newTime.getDate(); return year + "-" + (month >= 10 ? month : "0" + month) + "-" + (day >= 10 ? day : "0" + day); }; this.getWeekHtml = function(f, l) { return this.formateDate(f) + "" + this.formateDate(l); }; } var getWeek = new getWeek(); var week = getWeek.init().getWeekType(weeks); return week; }

 

js获取当月最后一天

//获取当月最后一天
    function getMonthLastDay(){
        var date=new Date();
        var currentMonth=date.getMonth();
        var nextMonth=++currentMonth;
        var nextMonthFirstDay=new Date(date.getFullYear(),nextMonth,1);
        var oneDay=1000*60*60*24;
        return new Date(nextMonthFirstDay-oneDay).getDate();
    }

 

js获取静态页面传值解析

调用:var uid =  UrlParm.parm("id")+"";  //这里UrlParm.parm("id")获取的值不是字符串类型的
/**
 * 静态页面之间传值
 * @returns {___anonymous_UrlParm}
 */
UrlParm = function() { // url参数  
      var data, index;  
      (function init() {  
        data = [];  
        index = {};  
        var u = window.location.search.substr(1);  
        if (u != '') {  
          var parms = decodeURIComponent(u).split('&');  
          for (var i = 0, len = parms.length; i < len; i++) {  
            if (parms[i] != '') {  
              var p = parms[i].split("=");  
              if (p.length == 1 || (p.length == 2 && p[1] == '')) {// p | p=  
                data.push(['']);  
                index[p[0]] = data.length - 1;  
              } else if (typeof(p[0]) == 'undefined' || p[0] == '') { // =c | =  
                data[0] = [p[1]];  
              } else if (typeof(index[p[0]]) == 'undefined') { // c=aaa  
                data.push([p[1]]);  
                index[p[0]] = data.length - 1;  
              } else {// c=aaa  
                data[index[p[0]]].push(p[1]);  
              }  
            }  
          }  
        }  
      })();  
      return {  
        // 获得参数,类似request.getParameter()  
        parm : function(o) { // o: 参数名或者参数次序  
          try {  
            return (typeof(o) == 'number' ? data[o][0] : data[index[o]][0]);  
          } catch (e) {  
          }  
        },  
        //获得参数组, 类似request.getParameterValues()  
        parmValues : function(o) { //  o: 参数名或者参数次序  
          try {  
            return (typeof(o) == 'number' ? data[o] : data[index[o]]);  
          } catch (e) {}  
        },  
        //是否含有parmName参数  
        hasParm : function(parmName) {  
          return typeof(parmName) == 'string' ? typeof(index[parmName]) != 'undefined' : false;  
        },  
        // 获得参数Map ,类似request.getParameterMap()  
        parmMap : function() {  
          var map = {};  
          try {  
            for (var p in index) {  map[p] = data[index[p]];  }  
          } catch (e) {}  
          return map;  
        }  
      }  
    }();  

 

 

js html5 和高德地图的定位

页面需要引入  <script type="text/javascript" src="https://webapi.amap.com/maps?v=1.4.12&key=411b5709c85b587ec7fc9e791ba171d5"></script>
/*
* * 地图定位,获取坐标并解析成地址 */ function getLocation_(ele,tag){ var map = new AMap.Map('container', { resizeEnable: true }); AMap.plugin('AMap.Geolocation', function() { var geolocation = new AMap.Geolocation({ enableHighAccuracy: true,// 是否使用高精度定位,默认:true timeout: 10000, // 超过10秒后停止定位,默认:5s buttonPosition:'RB', // 定位按钮的停靠位置 buttonOffset: new AMap.Pixel(10, 20),// 定位按钮与设置的停靠位置的偏移量,默认:Pixel(10, // 20) zoomToAccuracy: true, // 定位成功后是否自动调整地图视野到定位点 }); map.addControl(geolocation); geolocation.getCurrentPosition(function(status,result){ if(status=='complete'){ var pr = result.position+""; judgeClockState(pr,ele,tag); }else{ alert("定位失败") judgeClockState(0,ele,tag); } }); }); } function judgeClockState(n,ele,tag){ var address = ""; // 用来解析地址 // 定位成功 if(n!=0){ regeocoder(n,ele,tag); }else{ // 定位失败 alert("定位失败.请重新获取定位") } } function regeocoder(loc,ele,tag) { // 逆地理编码 var geocoder = new AMap.Geocoder({ radius: 1000, extensions: "all" }); geocoder.getAddress(loc, function(status, result) { if (status === 'complete' && result.info === 'OK') { console.dir(result); geocoder_CallBack(result,ele,tag); } }); var marker = new AMap.Marker({ // 加点 map: map, position: loc }); map.setFitView(); } function geocoder_CallBack(data,ele,tag) { var address = data.regeocode.formattedAddress; // 返回地址描述 document.getElementById("XYZ").innerHTML = address; alert(address); }

 

jquery/js将横向滚动条滚动到指定的位置

$('#div-0-1').scrollLeft(500);

 

js判断时长

// 判断时长是否为负数
function judgment(){
    var startDateTime = $("#startDate").val()+" "+$("#startTime").val()+":00";
    var endDateTime =  $("#endDate").val()+" "+$("#endTime").val()+":00";
    var d2 = new Date(endDateTime.replace(/\-/g, "/"));
    var d1 = new Date(startDateTime.replace(/\-/g, "/"));
    
    var times = parseInt(d2 - d1);
    if(times<0){
        alert("亲! 您选的结束时间不能小于开始时间")
    }
    return d1+"H"+d2;
}

 

 

 

 

webapp前端html5调用手机拍照功能,只适用于打包的webapp,浏览器,网页端不支持

/**
 * 拍照上传图片
 */
var ph_id;
var ph_ele;
function getPhoto(id,ele){
    ph_id = id;
    ph_ele = ele;
    getImg()
}
function getImg() {
    var bts = [ {
        title : "拍照"
    }, {
        title : "从相册选择"
    } ];
    plus.nativeUI.actionSheet({
        cancel : "取消",
        buttons : bts
    }, function(e) {
        if (e.index == 1) {
            getImage();
        } else if (e.index == 2) {
            galleryImgs();
        }
    });
}
function getImage() {
    var cmr = plus.camera.getCamera();
    cmr.captureImage(function(p) {
        plus.io.resolveLocalFileSystemURL(p, function(entry) {    
            compressImage(entry.toLocalURL(),entry.name);
            }, function(e) {
                plus.nativeUI.toast("读取拍照文件错误:" + e.message);
            });
        }, function(e) {
        
        }, {
            filter: 'image'
        });
}
// 从相册选择照片
function galleryImgs() {
    plus.gallery.pick(function(e) {
        var name = e.substr(e.lastIndexOf('/') + 1);
        compressImage(e,name);
    }, function(e) {
        
    },{
        filter: "image"
    });
}
// 压缩图片
function compressImage(url,filename){
    var name="_doc/upload/"+filename;
    plus.zip.compressImage({
        src:url,// src: (String 类型 )压缩转换原始图片的路径
        dst:name,// 压缩转换目标图片的路径
        quality:40,// quality: (Number 类型 )压缩图片的质量.取值范围为1-100
        overwrite:true// overwrite: (Boolean 类型 )覆盖生成新文件
    },function(zip) {
        console.log('图片压缩后路径'+zip.target)
        createUpload(zip.target)
    },function(error) {
        plus.nativeUI.toast("压缩图片失败,请稍候再试");
    });
}
function createUpload(url){
    // 服务器地址
    var hostport=document.location.host;
    var server="http://"+hostport+"/x5/x5/fileUtil/outOfFileUploadServer?uid="+ph_id;
    var wt=plus.nativeUI.showWaiting();
    var task=plus.uploader.createUpload(server,
          {method:"POST"},
        function(t,status){
        // 上传完成
           if(status==200){
            wt.close();
                // 服务端返回的结果
               var result = JSON.parse(t.responseText);
            console.log("上传成功返回结果:"+result);
             if(result.state=="success"){
                 $("<div onclick=amplification(this) href='#animatedModal_'><img src='/x5/file_upload/img/"+result.name+"' _src='"+result.name+"'></div>").prependTo($(ph_ele).next().find(".showImgs"))
             }else{
                 alert("上传失败,请重新拍照...")
             }
        }else{
            console.log("上传失败:"+status);
            wt.close();
        }
   });
   //将文件添加到上传队列中
   task.addFile(url,{key:'file'});
   task.start();
}

 

posted @ 2019-02-18 11:01  韩若明瞳  阅读(381)  评论(0编辑  收藏  举报