FullCalendar v5.3.2版本製作一個航班日曆Demo

千夜大魔王發表於2020-11-10

今天一個新需求是製作一個航班日曆來訂艙。然後我就各種找,最後找到FullCalendar,過程非常煎熬,網上例子大部分沒用,大部分沒有完整版。官網教程又不是很詳細。搞了幾天才徹底搞好這個航班日曆,所以我將程式碼記錄下來,供自己和網友參考

先看看成型的模樣:

 

 

廢話不多說。上程式碼:

 前端程式碼:

<!DOCTYPE html>
<meta charset='utf-8' />
<html lang="zh" xmlns:th="http://www.thymeleaf.org" >
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('新增訂艙')" />
    <!--引入FullCalendar css和js 自己去FullCalendar官網下載-->
    <link href='/cargo/css/main.css' rel='stylesheet' />
    <script src="/cargo/js/main.js"/>

    <!--載入日曆裡面的航班資料-->
    <script type="text/javascript">
        // <div id='Calendar'></div> 官網是放這裡,我放這裡不行,所以我放下面了
    </script>
    <style>
        body {
            margin: 40px 10px;
            padding: 0;
            font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
            font-size: 14px;
        }

        #Calendar {
            max-width: 1500px;
            margin: 0 auto;
        }

        /* Event 引數 className 的值 */
        .doing:before {
            content:"【 未完成 】";
            background-color:yellow;
            color:red;
            text-align:center;
            font-weight:bold;
        }
    </style>
</head>

<body class="gray-bg">
<div class="wrapper animated fadeInRight ">
    <div hidden class="form-group" style="margin-left: 75px">
        <a  class="btn btn-success disabled" id="bookFlightAdd" name="bookFlightAdd" onclick="$.operate.add()" shiro:hasPermission="freight:bookFlight:add">
            <i class="fa fa-plus"></i> 訂艙
        </a>
        <input type="hidden" id="flightData" value="">
        <a display  id="bookFlightHidden" name="bookFlightHidden" onclick="$.operate.addFlightData($('#flightData').val())" shiro:hasPermission="freight:bookFlight:add"></a>
    </div>

    <!--航班日曆-->
    <div id='Calendar'></div>
</div>

<th:block th:include="include :: footer" />
<script type="text/javascript">
    var prefix = ctx + "freight/bookFlight";

    <!--載入日曆裡面的航班資料-->
    document.addEventListener('DOMContentLoaded', function() {
        var calendarEl = document.getElementById('Calendar');
        var calendar = new FullCalendar.Calendar(calendarEl, {
            initialView: windowSize(), //日曆載入時的初始檢視
            timeZone: 'UTC',//時區
            editable: false,//是否可以修改日曆事件
            eventStartEditable:false,//允許事件的開始時間可通過拖動進行編輯
            eventDurationEditable:false,//允許通過調整大小來更改事件的持續時間
            themeSystem: 'bootstrap',//主題
            locale: 'zh',//語言
            headerToolbar: {//頭部工具欄
                left: 'prev,next today',
                center: 'title',
                right: headerToolbarRight()
            },
            dateClick: function(info) {//滑鼠點選
                info.dayEl.style.backgroundColor = '#00FF99';
            },
            buttonText:{//按鈕文字
                today:    '今天',
                month:    '',
                week:     '',
                day:      '',
            },
            initialDate: new Date(),//初始化時間
            navLinks: true, // 可以點選天/周的名稱來瀏覽檢視嗎
            dayMaxEvents: true, // 允許 "更多" 連結 當太多的事件
            dayMaxEventRows: true, // 用於所有非時間網格檢視
            moreLinkClick:"week",  //點選more按鈕時候,跳到什麼檢視
            //滑鼠懸浮提示 event.event.title
            eventMouseEnter : function( event ) {
                $(".fc-daygrid-event").attr("title",'點選訂艙');
            },

            //進入日曆介面進行載入新增過的資料
            events: function( fetchInfo, successCallback, failureCallback ){
                var events = [];
                $.ajax({
                    type:"POST",
                    url:prefix+"/viewData",
                    dataType:"json",
                    success:function(result){
                        var jobScheduleList =  result;
                        if(jobScheduleList.length > 1){
                            $.each(jobScheduleList,function(i,j){
                                events.push({
                                    //id:j.id,
                                    title: j.name,
                                    //url: prefix+j.url,//設定連結
                                    content:'$.operate.add()',//內容(我自己定義的,框架沒有)
                                    imageUrl:'/profile/'+j.imgUrl,//圖片連結(我自己定義的,框架沒有)
                                    color: 'pink',//設定顏色
                                    start: new Date(j.startDate).format('yyyy-MM-dd'), // 解析時間
                                    //end:new Date(j.endDate).format('yyyy-MM-dd')
                                    //className: 'doing',//設定類名
                                    //backgroundColor: 'gray',//設定背景顏色
                                });
                            })
                            //回撥渲染日曆
                            successCallback(events);
                        }
                    },
                    error:function(){
                        //出現錯誤回撥
                    },
                })
            },

            //航空公司圖片注入
            eventContent: function(arg) {
                let italicEl = document.createElement('span')
                if (arg.event.extendedProps.isUrgent) {
                    italicEl.onclick(setTimeout());
                    italicEl.innerHTML = '<img src="'+arg.event.extendedProps.imageUrl+'" width="30px" height="30px" style="border-radius: 15px;">'+' '+'<span>'+arg.event.title+'</span>';
                } else {
                    function abc() {
                        $('#flightData').val(arg.event.title);
                        // IE瀏覽器
                        if(document.all) {
                            document.getElementById("bookFlightHidden").click();
                        }
                        // 其它瀏覽器
                        else {
                            var e = document.createEvent("MouseEvents");
                            e.initEvent("click", true, true);
                            document.getElementById("bookFlightHidden").dispatchEvent(e);
                        }
                    }
                    italicEl.onclick=abc;
                    italicEl.innerHTML = '<img src="'+arg.event.extendedProps.imageUrl+'" width="30px" height="30px" style="border-radius: 15px;">'+' '+'<span>'+arg.event.title+'</span>';
                }
                let arrayOfDomNodes = [ italicEl ]
                return { domNodes: arrayOfDomNodes }
            },
        });
        calendar.render();
    });

    //判斷視窗大小來顯示不同的檢視(手機端不支援月檢視)
    function windowSize(){
        if(window. innerWidth< 800){
            return 'dayGridWeek';
        } else {
            return 'dayGridMonth';
        }
    }
    //判斷視窗大小來設定頭工具欄(手機端不支援月檢視)
    function headerToolbarRight(){
        if(window. innerWidth< 800){
            return 'dayGridWeek,dayGridDay';
        } else {
            return 'dayGridMonth,dayGridWeek,dayGridDay';
        }
    }

    //將資料庫的時間戳轉成 字串
    Date.prototype.format = function(format) {
        var o = {
            "M+": this.getMonth() + 1,
            "d+": this.getDate(),
            "h+": this.getHours(),
            "m+": this.getMinutes(),
            "s+": this.getSeconds(),
            "q+": Math.floor((this.getMonth() + 3) / 3),
            "S": this.getMilliseconds()
        }
        if (/(y+)/.test(format)) {
            format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        }
        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
            }
        }
        return format;
    }

        $(function () {
        var options = {
            createUrl: prefix + "/add",
            createCustomUrl: prefix + "/customAdd/{data}",
            modalName: "訂艙",
        };
        $.table.init(options);
    });
</script>
</body>
</html>

 

後端程式碼:

/**
 * 航班日曆
 * @author 千夜大魔王
 * @create 2020-11-03 10:19
 */
public class FlightCalendar {
    public FlightCalendar() {
    }

    public FlightCalendar(int id, String name, String content, String url, String imgUrl, Date startDate, Date endDate) {
        this.id = id;
        this.name = name;
        this.url = url;
        this.imgUrl = imgUrl;
        this.content = content;
        this.startDate = startDate;
        this.endDate = endDate;
    }

    public int id ;
    /**名稱*/
    public String name ;
    /**內容*/
    public String content ;
    /**連結*/
    public String url ;
    /**圖片連結*/
    public String imgUrl ;
    /**開始時間*/
    public Date startDate ;
    /**結束時間*/
    public Date endDate ;


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }

    public Date getStartDate() {
        return startDate;
    }

    public void setStartDate(Date startDate) {
        this.startDate = startDate;
    }

    public Date getEndDate() {
        return endDate;
    }

    public void setEndDate(Date endDate) {
        this.endDate = endDate;
    }
}
    /**
     * 載入航班日曆
     * @param
     * @return
     */
    @RequiresPermissions({"freight:bookFlight:list"})
    @PostMapping({"/viewData"})
    @ResponseBody
    public List<FlightCalendar> ViewData() {

        //查詢航班計劃
        CargoFlightSchedule cargoFlightSchedule=new CargoFlightSchedule();
        cargoFlightSchedule.setStatue("1");
        cargoFlightSchedule.setBookStatue("3");
        cargoFlightSchedule.setFlightTime(new Date());
        List<CargoFlightSchedule> list = cargoFlightScheduleService.selectCargoFlightScheduleANDAirlinesCompanyList(cargoFlightSchedule);

        List<FlightCalendar> flightCalendars=new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String title = list.get(i).getFlightNumber()+" "+list.get(i).getDeparturePort()+"-"+list.get(i).getDestination()+" "+DateUtil.format(list.get(i).getFlightTime(),"yyyy-MM-dd");
            flightCalendars.add(new FlightCalendar(i,
                            title,
                    "cargoFlightSchedules.get(i).getFlightNumber()",
                        "/add",
                            list.get(i).getaCimgUrl(),
                            list.get(i).getFlightTime(),
                            list.get(i).getFlightTime()));
        }

        return flightCalendars;
    }

有問題或者建議可以留言.

如果有幫到您,請點個推薦可以嗎?謝謝

相關文章