1. 程式人生 > >WEB前端資源代碼:學習篇

WEB前端資源代碼:學習篇

cli https 方法 是否 高德 per listener web前端 tla

1.JS設計模式片段

Function.prototype.addMethod = function (name,fn) {
   this.prototype[name] = fn;
   return this;
};
var Methods = function(){};
Methods.addMethod(‘checkName‘,function () {
   //驗證姓名
   console.log(‘姓名‘);
}).addMethod(‘checkEmail‘,function () {
   //驗證郵箱
   console.log(‘郵箱‘);
});
var m = new Methods();
m.checkName();
m.checkEmail();

2.canvas圖片預加載及進度條的實現

/*star
 *loading模塊
 *實現圖片的預加載,並顯示進度條
 *參數:圖片數組對象,加載完成的回調函數
 */
function loadImages(sources,callback){    
    var loadedImages = 0;    
    var numImages = 0;  
    ctx.font=‘14px bold‘;
    ctx.lineWidth=5;
    var clearWidth=canvas.width;
    var clearHeight=canvas.height;
    // get num of sources    
    for (var src in sources) {    
        numImages++;    
    }    
    for (var src in sources) {    
        images[src] = new Image();
        //當一張圖片加載完成時執行    
        images[src].onload = function(){ 
            //重繪一個進度條
            ctx.clearRect(0,0,clearWidth,clearHeight);
            ctx.fillText(‘Loading:‘+loadedImages+‘/‘+numImages,200,280);
            ctx.save();
            ctx.strokeStyle=‘#555‘;
            ctx.beginPath();
            ctx.moveTo(200,300);
            ctx.lineTo(600,300);
            ctx.stroke();
            ctx.beginPath();
            ctx.restore();
            ctx.moveTo(200,300);
            ctx.lineTo(loadedImages/numImages*400+200,300);  
            ctx.stroke();
            //當所有圖片加載完成時,執行回調函數callback
            if (++loadedImages >= numImages) {    
                callback();    
            }    
        };  
        //把sources中的圖片信息導入images數組  
        images[src].src = sources[src];    
    }    
}    
//定義預加載圖片數組對象,執行loading模塊
window.onload = function(){    
    var sources = {    
        PaperBoy1: "images/run/PaperBoy1.png",    
        PaperBoy2: "images/run/PaperBoy2.png", 
        PaperBoy3: "images/run/PaperBoy3.png",    
        PaperBoy4: "images/run/PaperBoy4.png" 
    };    
    //執行圖片預加載,加載完成後執行main
    loadImages(sources,main);    
};   
/*end*/

3.JS實現跨瀏覽器添加事件與移除事件怎樣做才最優?

一般的兼容做法,如下:

跨瀏覽器添加事件

//跨瀏覽器添加事件
    function addEvent(obj,type,fn){
        if(obj.addEventListener){
            obj.addEventListener(type,fn,false);
        }else if(obj.attachEvent){//IE
            obj.attchEvent(‘on‘+type,fn);
        }
    }

跨瀏覽器移除事件

//跨瀏覽器移除事件
function removeEvent(obj,type,fn){
    if(obj.removeEventListener){
        obj.removeEventListener(type,fn,false);
    }else if(obj.detachEvent){//兼容IE
        obj.detachEvent(‘on‘+type,fn);
    }
}

推薦寫法

    function addEvent( obj, type, fn ) {
      if ( obj.attachEvent ) {
        obj[‘e‘+type+fn] = fn;
        obj[type+fn] = function(){obj[‘e‘+type+fn]( window.event );}
        obj.attachEvent( ‘on‘+type, obj[type+fn] );
      } else
        obj.addEventListener( type, fn, false );
    }
    function removeEvent( obj, type, fn ) {
      if ( obj.detachEvent ) {
        obj.detachEvent( ‘on‘+type, obj[type+fn] );
        obj[type+fn] = null;
      } else
        obj.removeEventListener( type, fn, false );
    }

參考地址:

addEvent() recoding contest entry

addEvent() – Follow Up

4.Ajax用jsonp方式跨域發送請求小實例

眾所周知,Ajax是通過創建XMLHttpRequest對象或ActiveXObject來連接服務器、發送請求以及響應數據,但它卻不能跨域。而在分布式系統中我們又需要跨域發送接受數據,於是jsonp出現了...

它是一種跨域請求方式,主要利用了script標簽裏的src屬性,該屬性可以跨域發送請求,然後服務器返回js代碼,網頁端便響應其信息,然後我們可以對其傳過來的js代碼做處理提取其中的信息。

jsonp發送請求只需在src後面添加“?callback=函數名”就可以,例如“http://www.item.com/list?callback=myfunction",則只需在服務端接受參數myfunction並將函數名與想要返回的數據拼接就可以例如在java中響應該請求,可以獲取參數callback的值myfunction,再拼接成myfunction+"("+data+")"格式返回就行,在前端寫同名函數接受data並處理就可以了。但在jquery中對jsonp進行了封裝,返回函數就是success,數據也用success接受。

例如:

前端代碼:

//發送請求  
$.ajax({  
   //url:"http://localhost:8081/rest/itemcat/list?callback=getMessage",  
    url:"http://localhost:8081/rest/itemcat/message",      
    type:"get",  
    cache:false,  
    dataType:"jsonp",  
    jsonp:"callback", //這裏定義了callback的參數名稱,以便服務獲取callback的函數名即getMessage  
    jsonpCallback:"getMessage", //這裏定義了jsonp的回調函數  
    success:function(data){  
        alert("success:"+data);  
    },  
    error:function(){  
        alert("發生異常");  
    }  
});  

function getMessage(jsonp){  
    alert("message:"+jsonp);  
}

這樣發出的請求為:http://localhost:8081/rest/itemcat/message?callback=getMessage
jsonp:"callback",
jsonpCallback:"getMessage",
這兩個參數的值會自動拼接在url後面,所以用jquery的$.ajax方法發出的url可以不用在後面添加callback=getMessag,返回函數則變為了success而不是getMessage

5.使用高德地圖API創建地圖以及獲取當前地址經緯度

創建API地圖帶有點標記

<script src="http://webapi.amap.com/maps?v=1.4.1&key=bcf87f3263f98cc37309298bca20c622"></script>
<script type="text/javascript">
    // 實例化點標記
 function addMarker() {
        marker = new AMap.Marker({
            icon: "http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
            position: [116.41, 39.91]
        });
        marker.setMap(map);
    }

 var map = new AMap.Map(container, {
        resizeEnable: true,
        center: [116.40, 39.91],
        zoom: 13
    });
 addMarker();
</script>

根據瀏覽器定位獲取當前經緯度

<div id="container_display"></div>
<script src="https://webapi.amap.com/maps?v=1.4.1&key=bcf87f3263f98cc37309298bca20c622"></script>
<script>
function loadingCurrentPosition(callback){
    
    document.getElementById(container_display).innerHTML = ‘‘;
      //加載地圖,調用瀏覽器定位服務
    map = new AMap.Map(container_display, {
        resizeEnable: true
    });
    map.plugin(AMap.Geolocation, function() {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位,默認:true
            timeout: 10000,          //超過10秒後停止定位,默認:無窮大
            buttonOffset: new AMap.Pixel(10, 20),//定位按鈕與設置的停靠位置的偏移量,默認:Pixel(10, 20)
            zoomToAccuracy: true,      //定位成功後調整地圖視野範圍使定位位置及精度範圍視野內可見,默認:false
            buttonPosition:RB
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, complete, onComplete);//返回定位信息
        AMap.event.addListener(geolocation, error, onError);      //返回定位出錯信息
    });
    //解析定位結果
    function onComplete(data) {
        var getLngdata = data.position.getLng();
        var getLatdata = data.position.getLat();
        if(callback){
            callback(getLngdata,getLatdata); //回調參數中傳遞經度與緯度
        }
    }
    //解析定位錯誤信息
    function onError(data) {
        alert(定位失敗);
    }
}

$(function(){
    var getLng = ‘‘; //存經度
    var getLat = ‘‘; //存緯度
    //默認加載一次自動獲取當前人的位置
    loadingCurrentPosition(function(lngdata,Latdata){
        getLng = lngdata;
        getLat = Latdata;
    });
    $(".getCurrentPosition").on(click,function(){
        loadingCurrentPosition(function(lngdata,Latdata){
            getLng = lngdata;
            getLat = Latdata;
        });
    });
})

</script>

高德地圖根據瀏覽器定位獲取當前經緯度API案例地址:http://lbs.amap.com/api/javascript-api/example/location/browser-location
高德開放平臺:http://lbs.amap.com/api

6.JS創建canvas學習小例代碼

1.HTML5中的Canvas標簽的創建

window.onload = function(){
     createCanvas();
}
function createCanvas(){
    var canvas_width= 200, canvas_height = 200;
    document.body.innerHTML = "<canvas id=\"canvas\" width=\""+canvas_width+"\" height=\""+canvas_height+"\"></canvas>";
}

2.HTML5Canvas標簽繪制圖形

var canvas_width= 500, canvas_height = 500;
var mycanvas, context;
window.onload = function(){
    createCanvas();
    drawRect();
}
function createCanvas(){
   document.body.innerHTML = "<canvas id=\"mycanvas\" width=\""+canvas_width+"\" height=\""+canvas_height+"\"></canvas>";
   mycanvas = document.getElementById("mycanvas");
   context = mycanvas.getContext("2d");
}
 
function drawRect(){
    context.fillStyle ="#FF0000";
    //context.rotate(45);//旋轉45度
    //context.translate(200,200);//移動
    //context.scale(2,0.5);//縮放
    context.fillRect(0,0,200,200);
 }

3.HTML5Canvas標簽繪制圖片

var canvas_width= 500, canvas_height = 500;
var mycanvas, context;
window.onload = function(){
    createCanvas();
    drawImage();
}
function createCanvas(){
    document.body.innerHTML = "<canvas id=\"mycanvas\" width=\""+canvas_width+"\" height=\""+canvas_height+"\"></canvas>";
    mycanvas = document.getElementById("mycanvas");
    context = mycanvas.getContext("2d");
}
 
function drawImage(){
    var img = new Image();
    img.onload = function(){
        context.drawImage(img,0,0);
    }
     img.src = "1.png";
}

WEB前端資源代碼:學習篇