美文网首页Node让前端飞Web前端之路
前端日常笔记#1-实用代码片段

前端日常笔记#1-实用代码片段

作者: AlessiaLi | 来源:发表于2016-12-07 16:06 被阅读195次

    ajax 请求

    $.ajax({
          type: 'POST',
          url: '',
          data: {
            postVar1: 'theValue1',
            postVar2: 'theValue2'
          },
          beforeSend: function() {
            // this is where we append a loading image
            // 在这里我们展示 loading 信息(图片或者文字)
            $('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
          },
          success: function(data) {
            if (data.status) {
              // 返回数据正常
              // 删除 loading 效果并处理数据 data.data     
            } else {
              // 返回数据异常
              // 删除 loading 效果并给予用户适当反馈信息
              console.log('返回数据异常');
            }
          },
          error: function() {
            // failed request; give feedback to user
            // 数据请求失败,给用户适当的反馈信息
            console.log('数据请求失败');
            $('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
          },
          dataType: 'json'
    });
    
    // minimal
    $.ajax({
      type: 'POST',
      url: '',
      data: {
        postVar1: 'theValue1',
        postVar2: 'theValue2'
      },
      success: function(data) {
        if (data.status) {
          // 返回数据正常
        } else {
          // 返回数据异常
          console.log('返回数据异常');
        }
      },
      error: function() {
        // failed request; give feedback to user
        // 数据请求失败,给用户适当的反馈信息
        console.log('数据请求失败');
      },
      dataType: 'json'
    });
    

    json 格式

    {
        "status": 1,
        "info": "",
        "data": [……]
    }
    
    <!--空数据时-->
    {
        status: 0,
        info: "",
        data: []
    }
    

    回到上一页

    <button onclick="goBack()">Go Back</button>
    <script>
    function goBack() {
        window.history.back();
    }
    </script>
    

    图片占位背景色

    var w = $(document.body).width()*0.455;
    $('.benefits_list .col-6 a').width(w);
    $('.benefits_list .col-6 a').height(w*450/960);
    

    default btn

    .btn{
        display: inline-block;
        padding: 6px 12px;
        margin-bottom: 0;
        font-size: 14px;
        font-weight: 400;
        line-height: 1.42857143;
        text-align: center;
        white-space: nowrap;
        vertical-align: middle;
        cursor: pointer;
        border: 1px solid transparent;
        border-radius: 4px;
    }
    .btn-default{
        color: #333;
        background-color: #fff;
        border-color: #ccc;
    }
    

    计算时间差(天)

    /*-------------------判断时间差 start---------------------*/
    // From 2016-09-30 10:33 to "09/30/2016"(mm/dd/yyyy)
    function dateFormat(someday){
        var date = someday.split(' ')[0];
        var dateArr = date.split('-');
        var result = [];
        result[0] = dateArr[1];
        result[1] = dateArr[2];
        result[2] = dateArr[0];
        return result.join('/');
    }
    
    // a and b are javascript Date objects
    function dateDiffInDays(a, b) {
      var _MS_PER_DAY = 1000 * 60 * 60 * 24;
      // Discard the time and time-zone information.
      var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
      var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
    
      return Math.floor((utc2 - utc1) / _MS_PER_DAY);
    }
    
    // 判断相差几天?今天或者7天前
    // 今天 today:var today = new Date();
    // 某天 before:2016-09-30 10:33
    function dateDiff(today,before){
        var someday = new Date(dateFormat(before));
        return dateDiffInDays(someday,today);
    }
    /*-------------------判断时间差 end---------------------*/
    

    判断当前时间在指定时间的前后

    var nowDate=new Date();
    var now = nowDate.getTime();
    var endDate = '2016/8/10 09:39:00';
    var end = new Date(endDate).getTime();
    if(end<=now){
        ...
    }else{
        ...
    }
    

    sticky footer

    function sticky($footer){
        var offset = $footer.offset();
        var windowH = $(window).height();
        var footerH = $footer.height();
        if((offset.top+footerH) < windowH){
            var diff = windowH - (offset.top+footerH);
            var top = (parseInt($footer.css('top')) + diff) + "px";
            $footer.css('top', top);
        }
    }
    

    动态添加的内容渐显

    html

    <div class="fade"></div>
    

    css

    .fade {
        opacity: 0;
        -webkit-transition: opacity .15s linear;
        -o-transition: opacity .15s linear;
        transition: opacity .15s linear;
    }
    .fade.in {
        opacity: 1;
    }
    

    js

    setTimeout(function(){
        $('.fade').addClass('in');
    },100);
    
    <!--example-->
    function showFeedback(txt, duration){
        $('.modal-fb-tip').text(txt);
        $('.modal-fb').removeClass('hidden');
        setTimeout(function(){
            $('.modal-fb.fade').addClass('in');
        },100);
        setTimeout(function(){
            $('.modal-fb.fade.in').removeClass('in');
            setTimeout(function(){
                $('.modal-fb').addClass('hidden');
            },100);
        },duration);
    }
    

    判断是否是数字,且满足某个区间

    How do I check that a number is float or integer?

    // check for a remainder when dividing by 1:
    
    function isInt(n) {
       return n % 1 === 0;
    }
    
    //If you don't know that the argument is a number you need two tests:
    
    function isInt(n){
        return Number(n) === n && n % 1 === 0;
    }
    
    function isFloat(n){
        return Number(n) === n && n % 1 !== 0;
    }
    
    parseInt("a")
    ==> NaN
    isNaN(parseInt("a"))
    true
    isNaN(parseInt("1"))
    false
    

    replace broken img

    onerror="this.onerror=null;this.src='imagefound.gif';"
    

    绑定 input file 的 change 事件

    document.getElementById('upload-file').addEventListener('change', function(){
        previewFile($('.action-upload-view img')[0], $('#upload-file')[0]);
    })
    

    file 类型的 input 只接受图片类文件

    How to allow <input type=“file”> to accept only image files

    <input type="file" name="myImage" accept="image/*" />
    

    获取当前时间

    Getting current date and time in JavaScript

    // For the time now
    Date.prototype.timeNow = function(){ return ((this.getHours() < 10)?"0":"") + ((this.getHours()>12)?(this.getHours()-12):this.getHours()) +":"+ ((this.getMinutes() < 10)?"0":"") + this.getMinutes() +":"+ ((this.getSeconds() < 10)?"0":"") + this.getSeconds() + ((this.getHours()>12)?('PM'):'AM'); };
    
    // For todays date;
    Date.prototype.today = function () { 
        return ((this.getDate() < 10)?"0":"") + this.getDate() +"/"+(((this.getMonth()+1) < 10)?"0":"") + (this.getMonth()+1) +"/"+ this.getFullYear();
    }
    
    var newDate = new Date();
    var datetime = "LastSync: " + newDate.today() + " @ " + newDate.timeNow();
    // Output: "LastSync: 18/10/2016 @ 09:10:35AM"
    -----------------------------------------------
    -----------------------------------------------
    // For the time now
    Date.prototype.timeNow = function() {
        return ((this.getHours() < 10) ? "0" : "") + this.getHours() + ":" + ((this.getMinutes() < 10) ? "0" : "") + this.getMinutes() + ":" + ((this.getSeconds() < 10) ? "0" : "") + this.getSeconds(); };
    
    // For todays date;
    Date.prototype.today = function() {
        return this.getFullYear() + "-" + (((this.getMonth() + 1) < 10) ? "0" : "") + (this.getMonth() + 1) + "-" + ((this.getDate() < 10) ? "0" : "") + this.getDate();
    }
    
    var newDate = new Date();
    var datetime = newDate.today() + " " + newDate.timeNow();
    // Output: "2016-10-18 09:18:04"
    

    图片加载错误

    jQuery/JavaScript to replace broken images

    // 图片加载错误
    function imgError(image) {
        image.onerror = "";
        image.src = "../img/default.jpg";
        return true;
    }
    onerror="imgError(this);"
    

    移动端 input 框清除内阴影

    box-shadow: none;
    border: 0;
    outline: 0;*
    

    Get URL parameters using jQuery

    // Get URL parameters using jQuery
    // example.com?param1=name&param2=&id=6
    // $.urlParam('param1'); // name
    // $.urlParam('id');        // 6
    // $.urlParam('param2');   // null
    $.urlParam = function(name) {
        var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
        if (results == null) {
            return null;
        } else {
            return results[1] || 0;
        }
    }
    

    相关文章

      网友评论

      本文标题:前端日常笔记#1-实用代码片段

      本文链接:https://www.haomeiwen.com/subject/oyadmttx.html