jquery點擊圖片讓圖片顯示在屏幕中間

注意點:
1.解析圖片資源須要時間   因此設置定時器
2.從div裏面獲取的background屬性值   是絕對路徑  要轉化爲相對的

3.火狐和谷歌和ie獲取的background的路徑問題 css

<div class="hidden border pointer zm-image" id="preview" onclick=zmShow($(this))></div>
#preview{
	width:372px;
	height:325px;
}
//查找.zm-image裏面有無圖片
function hasPic($element){
	'use strict';
	var exist = $(".zm-image").attr("style");
	console.log(exist);
	if(exist == undefined)
		return false;
	//對於ie來講   exit解析出來是background: url("../../image/report/2013-07-31-78f35826.png")    
	//background: 冒號後面多了一個空格
	//檢測有無background屬性
	exist = exist.indexOf('background');
	if( exist >= 0)
		return true;
	else
		return false;		
}
function zmShow($e){
	console.log("show");
	if( hasPic($(this)) ){
		
		 //移除以前生成的彈出框
		$(".zm-imageWrap").remove();    
		var image = "<div class='zm-imageWrap'>" +
		"<div class='zm-imagepop'></div>" +
		"<img class='zm-imageInner'/>" +
		"</div>";
		//在body下加入彈出框
		$("body").append(image);
		$(".zm-imageWrap").hide();
		//path  獲得原始圖片的路徑
		var path = $e.css("background-image");
		path = path.substring(4,path.length-1);
		path = path.replace("http://localhost/afforest/","../../");
		//谷歌../../image/report/2013-07-31-1ec67d38.jpg ff:"../../image/report/2013-07-31-1ec67d38.jpg"
		//因此針對ff瀏覽器  去掉引號
		if(path[0] == '"')
			path = path.substring(1,path.length-1);
		console.log(path+"path");
		//path = "../"+$("#imagePath").val();                          //修改zs1314zt
		//添加路徑
		$("img.zm-imageInner").attr("src",path);
		//生成image類   計算原始圖片寬度和高度
		var originImage=new Image();
		originImage.src=path;
		//因爲image類解析圖片須要時間   設置延遲  得到高度和寬度
		window.setTimeout(function(){
			//把圖片的中心放在屏幕中心
			var Width = originImage.width;
			var Height = originImage.height;
			var zmleft = (window.innerWidth-Width)/2;
			var zmtop = (window.innerHeight-Height)/2;
			console.log(zmleft+"   "+zmtop+" "+ Width+" "+Height+" "+window.innerWidth+" "+window.innerHeight);
			$(".zm-imageInner").css("left",zmleft).css("top",zmtop);	
			$(".zm-imageWrap").show();
		}, 100);
	}
	$(".zm-imageWrap").click(function(){
		$(this).remove();
	});
}
相關文章
相關標籤/搜索