前端日常筆記#1-實(shí)用代碼片段

ajax 請(qǐng)求

$.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) {
          // 返回?cái)?shù)據(jù)正常
          // 刪除 loading 效果并處理數(shù)據(jù) data.data     
        } else {
          // 返回?cái)?shù)據(jù)異常
          // 刪除 loading 效果并給予用戶適當(dāng)反饋信息
          console.log('返回?cái)?shù)據(jù)異常');
        }
      },
      error: function() {
        // failed request; give feedback to user
        // 數(shù)據(jù)請(qǐng)求失敗,給用戶適當(dāng)?shù)姆答佇畔?        console.log('數(shù)據(jù)請(qǐng)求失敗');
        $('#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) {
      // 返回?cái)?shù)據(jù)正常
    } else {
      // 返回?cái)?shù)據(jù)異常
      console.log('返回?cái)?shù)據(jù)異常');
    }
  },
  error: function() {
    // failed request; give feedback to user
    // 數(shù)據(jù)請(qǐng)求失敗,給用戶適當(dāng)?shù)姆答佇畔?    console.log('數(shù)據(jù)請(qǐng)求失敗');
  },
  dataType: 'json'
});

json 格式

{
    "status": 1,
    "info": "",
    "data": [……]
}

<!--空數(shù)據(jù)時(shí)-->
{
    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;
}

計(jì)算時(shí)間差(天)

/*-------------------判斷時(shí)間差 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);
}
/*-------------------判斷時(shí)間差 end---------------------*/

判斷當(dāng)前時(shí)間在指定時(shí)間的前后

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);
    }
}

動(dòng)態(tài)添加的內(nèi)容漸顯

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);
}

判斷是否是數(shù)字,且滿足某個(gè)區(qū)間

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

獲取當(dāng)前時(shí)間

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"

圖片加載錯(cuò)誤

jQuery/JavaScript to replace broken images

// 圖片加載錯(cuò)誤
function imgError(image) {
    image.onerror = "";
    image.src = "../img/default.jpg";
    return true;
}
onerror="imgError(this);"

移動(dòng)端 input 框清除內(nèi)陰影

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;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,551評(píng)論 19 139
  • afinalAfinal是一個(gè)android的ioc,orm框架 https://github.com/yangf...
    passiontim閱讀 15,869評(píng)論 2 45
  • 感覺到人類是相當(dāng)偉大的物種,突破地獄文化的阻隔,通融互通,共同戰(zhàn)勝困難重重,生存并且不斷進(jìn)化創(chuàng)新
    螢火蟲的霞光閱讀 118評(píng)論 0 0
  • 日精進(jìn)打卡 姓名 溫州市博奕成套設(shè)備工程有限公司 組別 301期 利他一組 【日精進(jìn)打卡第021天】 【知~學(xué)...
    7bec976c3bf2閱讀 229評(píng)論 0 0
  • 杯蓋和杯身密不可分,但是杯身的心里卻裝著水,所以,在愛情中,在一個(gè)人的身邊,不一定在那個(gè)人的心里。 筆帽和筆蓋形影...
    趙小乖007閱讀 294評(píng)論 0 0

友情鏈接更多精彩內(nèi)容