`
xiao_2012_wei
  • 浏览: 30456 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
bootstrap框架使用 js框架使用
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Bootstrap的HTML标准模板</title>   
        <!-- Bootstrap -->
        <link href="css/bootstrap.min.css" rel="stylesheet">
        <!--你自己的样式文件 -->
        <link href="css/your-style.css" rel="stylesheet">        
        <!-- 以下两个插件用于在IE8以及以下版本浏览器支持HTML5元素和媒体查询,如果不需要用可以移除 -->
        <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
        <![endif]-->
    </head>
    <body>
        <h1>Hello, world!</h1>
        
        <!-- 如果要使用Bootstrap的js插件,必须先调入jQuery -->
        <script src="http://libs.baidu.com/jquery/1.9.0/jquery.min.js"></script>
        <!-- 包括所有bootstrap的js插件或者可以根据需要使用的js插件调用 -->
        <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script> 
    </body>
</html>
判断浏览器是否支持webp js小功能
/**
 * Created by wuchaowu on 2015/9/24.
 */
define("common_yhd_webp",function (){
    var exports = {};
    //根据配置的比例返回是否用webp
	 function strTrim(str) {
		    if(str && typeof(str) =="string"){
		    	  return str.replace(/(^\s*)|(\s*$)/g,'');
		    }else{
		    	return str;
		   }		  
	}
    //根据配置的比例返回是否用webp
    function useWebpPercent(){
        if(typeof(localStorage) == "undefined"){
            return false;
        }
        if(typeof(webPercent) =="undefined"){
            webPercent = 100;
        }
        var _rd = parseInt(Math.random()*100);
        try{
            if(localStorage.getItem("_webpPercent") ){
                _rd = localStorage.getItem("_webpPercent");
            }else{
                localStorage.setItem("_webpPercent",_rd);
            }
        }catch(err){};
        return	  webPercent<_rd?false:true;
    }
    function canUseWebP() {
        if(typeof(localStorage) == "undefined"){
            return false;
        }
        var localWebp = localStorage.getItem("webp");
        if(localWebp){
            return true;
        }
        var elem = document.createElement('canvas');

        if (!!(elem.getContext && elem.getContext('2d'))) {
            // was able or not to get WebP representation
            var result = elem.toDataURL('image/webp').indexOf('data:image/webp') == 0;
            if(result){
                localStorage.setItem("webp",true);
            }
            return result;
        }
        else {
            // very old browser like IE 8, canvas not supported
            return false;
        }
    }
    var isCanUserWebP = canUseWebP();
    if(isCanUserWebP){
        isCanUserWebP = 	useWebpPercent();
    }
    function _replaceWebP(imgUrl){
        if(!isCanUserWebP || !imgUrl){
            return imgUrl;
        }
        imgUrl = strTrim(imgUrl);
        var reg = /^(http|https):\/\/(d\d{1,2})/ ;
        if(imgUrl.search(reg) ==-1){
             return imgUrl;
        }
        var splitUrl = imgUrl.split(".");
        if(splitUrl.length>1){
        	//gif图片不做处理.
			if(splitUrl[splitUrl.length-1].toLowerCase() == "gif"){
				return imgUrl;
			}
            splitUrl[splitUrl.length-1] = "webp";
        }
        return splitUrl.join(".");
    }
    exports.replaceWebP = _replaceWebP;
    return exports;
})
js执行图片懒加载 js小功能
$P.LazyLoadPic = function(){
		$(window).scroll(function(){
			$P.initPic();
		});
		
	};

$P.initPic=function(){
 		var imgs = $('.content').find('img[original]');
 		console.log(imgs.length);
		var count = 5;
		for(var i=0,j=imgs.length; i<j; i+=count){
			var _img =  $(imgs[i]);
 			// 用图片的offset来判断
			if($(document).scrollTop() > (_img.offset().top-$(window).height())){
				for(var m=i,n=m+count; (m<n&&m<j); m++){
					var img =  $(imgs[m]);
					img.attr('src', img.attr('original')).removeAttr('original');
				}
			}
		}
	};
js倒计时 js小功能
//计时器
	$P.CountdownTime = function(){
		var activityStatus = $("#activityStatus").val();
		$(".timer").each(function() {
			var thisObj = $(this) ; //opt
			var remainSec = (thisObj.attr("data-remainTime")) / 1000;
			
			if (remainSec >= 0) {
				var msg = "";
				var second = Math.floor(remainSec % 60);// 计算秒
				var minute = Math.floor((remainSec / 60) % 60); // 计算分
				var hour = Math.floor((remainSec / 3600) % 24); // 计算小时
				var day = Math.floor((remainSec / 3600) / 24); // 计算天
				
				if(day >= 1){
					if(activityStatus==0){
						msg = day + "天   后开始"
					}else{
						msg = "剩余:" + day + "天";
					}
				}else if(day < 1){
					if(activityStatus==0){
						msg = hour + "时" + minute + "分" + second + "秒    后开始";
					}else{
						msg = "剩余:" + hour + "时" + minute + "分" + second + "秒";
					}
				}
				
				if (day == 0 && hour == 0 && minute == 0 && second == 0) {
					if(activityStatus==0){//即将开始状态,到开始,刷新页面
						window.location.reload();
					}else{//从已开始到结束
						thisObj.html("活动已到期");
						var linkObj = thisObj.parent().parent().attr("class");
						if(linkObj.attr("class") == "flashBuy"){
							linkObj.removeAttr("href").removeAttr("target");
						}
					}
				} else {
					thisObj.attr("data-remainTime", (remainSec - 1) * 1000).html(msg);	
				}
			}
		});
		window.setTimeout("PRODUCTLIST.CountdownTime()", 1000);
	};
图片hover放大效果 图片展示
/**
 * 放大图片展示
 * 喻文杰
 */
;(function($){
	
	var options={
		width:300,
		height:300,
		left:"",
		showWidth:true,
	}

	$.fn.showImage = function(opts){
		options = $.extend(true, options, opts);
		
		this.each(function(){
			if(!$(this).hasClass("img-rounded"))$(this).addClass("img-rounded");
			if(!$(this).hasClass("margin-auto"))$(this).addClass("margin-auto");
			
			
			$(this).off("mouseover").on("mouseover",function(event){
				var $this = $(this);
				var top = getTop($this);
				var left = getLeft($this);
				var src = $this.attr("src");
				if(domain+"/statics/backend/images/index.png" == src) return;
				var imageDiv = createImageDiv(src);
				var out = pointerEventToXY(event, $this, imageDiv);
				imageDiv.css({
					"display":"block",
					"top":out.y,
					"left":out.x
				});
			});

			$(this).off("mouseout").on("mouseout",function(){
				$('#showImageDiv').css({
					"display":"none"
				});
			});
			
			$(document).on("click",function(){
				$('#showImageDiv').css({
					"display":"none"
				});
				
			});
		});
	}

	$.fn.imageWidth = function(callBack){
		var url = $(this).attr("src");
		getImageWidth(url,callBack);
	}
	
	function pointerEventToXY(event,$selector,$imageDiv) {
		var out = {x:0, y:0};
		var x = $this.offset().left;
		var y = $this.offset().top - $(window).scrollTop();
		
		
		var left = x + $selector.width() + 5;
		var totalWidth = $(window).width();
		if(left + $imageDiv.width() > totalWidth){
			left = x - $imageDiv.width() - 5;
		}
		
		if(left < 0) left = 0;
		
		x = left;
		
		var top = y;
		var allHeight = $(window).height();
		
		if(top + $imageDiv.height() > allHeight ){
			top = allHeight - $imageDiv.height() - 50;
		}
		
		if(top < 0) top = 0;
		
		y = top;
		
		out.x = x;
		out.y = y;
		
		return out;
	};
	
	function getLeft(obj){
		
		if("" != options.left){
			return options.left;
		}else{
			$this = $(obj);
			var left = $this.offset().left;
			var totalWidth = $(window).width();
			
			if(left + options.width > totalWidth){
				left = left - options.width - 20;
			}else{
				left += $this.width()+20;
			}
			return left;
		}
	}

	
	function getTop(obj){
		$this = $(obj);
		var top = $this.offset().top;
		var allHeight = $(window).height();
		
		if(top + options.height > allHeight ){
			top = top - options.height + $this.height();
		}
		return top;
	}

	function createImageDiv(src){
		var $imageDiv;
		if($('#showImageDiv').length == 1){
			$imageDiv = $('#showImageDiv');
		}else{
			$imageDiv = $('<div class="thumbnail" id="showImageDiv"><div>')
			$imageDiv.css({
				"width":options.width+"px",
//				"height":options.height+"px",
				"position":"fixed",
				"display":"none",
				"z-index":999999
			})
			$('body').append($imageDiv);
		}
		var $img;
			
		if($imageDiv.find("img").length == 1){
			$img = $imageDiv.find("img");
		}else{
			$img = $('<img style="width: 100%;" />');
			$imageDiv.append($img);
		}
		
		$img.attr("src",src);
		
		if(options.showWidth){
			getImageWidth(src,function(w,h){
				var $carousel = $imageDiv.find(".carousel-caption h4");
				if($carousel.length>0){
					$carousel.text(w+" x "+h);
				}else{
					$carousel = $('<div contenteditable="true" style="border-radius: 50%;padding-bottom: 0px;padding-top: 0px;left: 30px;bottom: 10px;right: 30px;opacity: 0.5;" class="carousel-caption"><h4>'+(w+" x "+h)+'</h4></div>');
					$imageDiv.append($carousel);
				}
			});
		}
		return $imageDiv;
	}
	
	function getImageWidth(url,callback){ 
		var img = new Image(); 
		img.src = url; // 如果图片被缓存,则直接返回缓存数据 
		if(img.complete){
			callback(img.width, img.height); 
		}else{ // 完全加载完毕的事件 
			img.onload = function(){ 
				callback(img.width, img.height); 
			} 
		} 
	}
	
})($,jQuery);
js执行图片热区数据渲染 图片热区
/**
 *  热点切图前端显示 : 热点图片通用接口
 *   Created by wangliang3  2014 - 11 -4
 *  页面图片设置 <img data-imghot="ture" ...../>
 * ; 合并js文件,防止何必与之前的非正常函数冲突
 */
;jQuery(document).ready(function(){(function($, window){
    var imghotUtil = {
        isShow : true,
        imgs : [],
        mapKey : {
            area : 'area',
            info : 'info'
        },
        msg : {
            msgid : 'imgHotMsg'
        },
        //从数组中计算最大最小值
        getMaxMinFromArr : function(arr){
            var rs ={
                max : Math.max.apply(null, arr),
                min : Math.min.apply(null, arr)
            };
            return rs;
        },
        //得到当前页面的最大 z-index + 1
        getMaxZIndex : function(){
            // 负无穷大
            var highest = -Infinity;
            $("*").each(function() {
                var current = parseInt($(this).css("z-index"), 10);
                if(current && highest < current){
                    highest = current;
                };
            });
            return highest + 1;
        },
        //ajax请求方法
        getAjaxDatas : function (url,data,callBack){
            $.ajax(
                {
                    type : "get",
                    url:url,
                    data:data,
                    dataType : "jsonp",
                    jsonp: "callback",
                    jsonpCallback : "handlerShangouImgCut",
                    cache: true,
                    timeout: 5000,
                    error : function(result) {
                        try{
                            callBack(result);
                        }catch(e){
                            //console.error('imgHotCut,js error 加载异常:' + url);
                        }
                    },
                    success:function(result){
                        try{
                            callBack(result);
                        }catch(e){
                            //console.error('imgHotCut,js error 加载异常:' + url);
                        }
                    },
                    complete:function(e,t){
                        if(t && t == "timeout"){
                           // console.error('imgHotCut,js complete 加载超时:' + url);
                            callBack(t);
                        }
                    }
                }
            )
        },
        //Js 实现类似Java中的Map对象
        map : (function (){
            return new function() {
                var size = 0;
                var entry = new Object();

                this.put = function (key, value) {
                    if (!this.containsKey(key)) {
                        size++;
                    };
                    entry[key] = value;
                };
                this.get = function (key) {
                    if (this.containsKey(key)) {
                        return entry[key];
                    }else {
                        return null;
                    }
                };
                this.remove = function (key) {
                    if (delete entry[key]) {
                        size--;
                    }
                };
                this.containsKey = function (key) {
                    return (key in entry);
                };
                this.containsValue = function (value) {
                    for (var prop in entry) {
                        if (entry[prop] == value) {
                            return true;
                        }
                    }
                    return false;
                };
                this.values = function () {
                    var values = [];
                    for (var prop in entry) {
                        values.push(entry[prop]);
                    }
                    return values;
                };
                this.keys = function () {
                    var keys = [];
                    for (var prop in entry) {
                        keys.push(prop);
                    }
                    return keys;
                };
                this.size = function () {
                    return size;
                };
                this.clear = function () {
                    entry = new Object();
                };
                this.isEmpty = function () {
                    return size == 0 ? true : false;
                };
                this.getObjs = function (){
                    return entry;
                };
            }
        })(),
        //创建area元素唯一id
        getId : function(){
            if(this.map.containsKey(this.mapKey.area)){
                var num = this.map.get(this.mapKey.area) + 1;
                this.map.put(this.mapKey.area, num);
                return 'area_id' + num;
            }else{
                this.map.put(this.mapKey.area, 1);
                return 'area_id1';
            }
        },
        //得到时间戳 备用
        getTimestamp : function (){
            var timestamp = Date.parse(new Date());
            return timestamp;
        },
        getShapType : function(type){
            switch(type){
                case 1: return 'rect';
                    break;
                case 2: return 'circle';
                    break;
                case 3: return 'polygon';
                    break;
            };
        },
        //初始化图片数据map
        initImg : function (){
            $('img').each(function(i){
                if(this && $(this).attr('data-imghot') === 'true'){
                    var url = this.src,
                        usemap = 'usemap' + i;
                    $(this).attr('usemap', '#' + usemap);
                    this.usemap = usemap;
                    imghotUtil.map.put(url, this);
                };
            });
            return this;
        },
        //初始化area
        initArea : function(){
            if(!this.map.isEmpty()){
                var URLPrefix = URLPrefix || {};
                     URLPrefix.tuanmall = URLPrefix.tuanmall || 'http://t.yhd.com';
                     
                var url = URLPrefix.tuanmall + '/tuangou/squid/getHotImgCutInfo.do',
	                 keys = this.map.keys(),
	                 urls = keys.length == 1 ? keys[0] : keys.join(',');  //多数据用逗号隔开请求
                     if(isPreview == 1){
                    	 url += "?rd="+(Math.random());
                     }
                     var param = {'url' : urls,'brandPreview' : isPreview};
                     

                this.getAjaxDatas(url,param,function(resp){
                    if(resp=="null" || !resp.hasOwnProperty("data")){
                        //console.error('网络服务不给力: ' + url);
                        return;
                    };

                    $.each(resp.data, function(i, data){
                        var list = data.list,
                            url = data.url,
                            img = imghotUtil.map.get(url),
                            rs = imghotUtil.getImgMapHtml(img, list);
                            mapHtml = rs[0],
                            arr_info = rs[1];
                        $(img).parent().append(mapHtml);
                        //imghotUtil.bindEvents(arr_info, img);
                        imghotUtil.bindEventsToImg(arr_info, img);
                    });
                });
            };

            return this;
        },
        imgEvent : function(){
            if(this.imgs.length > 0){
                for(var i = 0, len = this.imgs.length; i < len ; i++){
                    this.imgs[i].target.bind({mouseover : function(e){

                    }
                    });

                }
            }
        },
        //得到图片map的html
        getImgMapHtml : function (obj, data) {
            var arr = [],
                rs = [],
                arr_info = [];
            arr.push('<map name="' + obj.usemap + '" id="' + obj.usemap + '">');
            $.each(data, function(i, item){
                var id = imghotUtil.getId();
                arr.push('<area id="' + id + '" shape="' + imghotUtil.getShapType(item.type) + '" coords="' + item.coords + '" action_type ="' + item.action_type + '" alt="" href="javascript:void(0)" />');
                item.id = id;
                arr_info.push(item);
            });
            arr.push('</map>');
            rs.push(arr.join(''));
            rs.push(arr_info);
            return rs;
        },
        //计算area的显示位置
        getAreaXY : function(area){
            var xy = {};
            switch(area.type){
                case 1: //矩形取中间位置
                    if(area.coords.indexOf(',')){
                        var arr = area.coords.split(','), x1 = +arr[0], y1 = +arr[1], x2 = +arr[2], y2 = +arr[3];
                        xy.x = Math.round(x1 + (x2 - x1)/2),
                        xy.y = Math.round(y1 + (y2 - y1)/2);
                    };
                    break;
                case 2: //圆形取圆心
                    if(area.coords.indexOf(',')){
                        var arr = area.coords.split(','), x1 = +arr[0], y1 = +arr[1];
                        xy.x = x1,
                            xy.y = y1;
                    };
                    break;
                case 3: //多边形切面的中心位置
                    if(area.coords.indexOf(',')){
                        var arr = area.coords.split(','),
                            arrX = [] ,arrY = [];
                        //递归分组
                        var pop = function (arr, a, b) {
                            arr.length && a.push(arr.shift());
                            arr.length && b.push(arr.shift());
                            arr.length && pop(arr, a, b);
                        }
                        pop(arr, arrX, arrY);

                        var maxminX = this.getMaxMinFromArr(arrX),
                            maxminY = this.getMaxMinFromArr(arrY);

                        xy.x = Math.round(maxminX.min + (maxminX.max - maxminX.min)/2),
                        xy.y = Math.round(maxminY.min + (maxminY.max - maxminY.min)/2);
                    };
                    break;
            }
            return xy;
        },
        //绑定事件给图片对象
        bindEventsToImg : function(arr_info, img){
            var dom,
                imgX = img.getBoundingClientRect().left + document.documentElement.scrollLeft + document.body.scrollLeft,
                imgY = img.getBoundingClientRect().top + document.documentElement.scrollTop + document.body.scrollTop,
                zindex = this.getMaxZIndex();
            //console.log('imgX : ' + imgX + ' imgY : ' + imgY);
            if(document.getElementById(imghotUtil.msg.msgid)){
                dom = $('#' + imghotUtil.msg.msgid);
            }else{
                dom = $("<span id='imgHotMsg'></span>");
                dom.css({
                    position : 'absolute',
                    background : 'red',
                    'z-index' : zindex,
                    display :   'none'
                }).appendTo('body');
            };

            //设置提示图片,自适应缩放
            var setDomImg = function(dom, url, wh, topLeft){

                //console.log(topLeft);
                var domCss = function(dom, url, wh, topLeft){
                    var top = Math.round(((+topLeft.top) - (+wh.height)/2))  + 'px';
                    var left =  Math.round(((+topLeft.left) - (+wh.width)/2))  + 'px';
                    //console.log('top : ' + top + '  left : ' + left);
                    dom.css({
                        top     : Math.round(((+topLeft.top) - (+wh.height)/2))  + 'px',
                        left    : Math.round(((+topLeft.left) - (+wh.width)/2))  + 'px',
                        background : 'url(' + url  + ')',
                        width  : wh.width,
                        height : wh.height,
                        cursor : 'pointer'
                    });
                };

                var newImg = new Image();
                newImg.src = img.src;
                var imgWh = {}, obj = $(img);
                if(newImg.complete){
                    imgWh = {
                        now_width : obj.width(),
                        now_heigh : obj.height(),
                        width: newImg.width,
                        height: newImg.height
                    };
                    //计算缩放
                    if(imgWh.now_width != imgWh.width || imgWh.now_heigh != imgWh.height){

                        topLeft.top  = Math.round((imgWh.now_heigh * topLeft.y)/imgWh.height) + topLeft.imgY;
                        topLeft.left = Math.round((imgWh.now_width * topLeft.x)/imgWh.width) + topLeft.imgX;

                    }

                    domCss(dom, url, wh, topLeft);
                }else {
                    newImg.onload = function () {
                        imgWh = {
                            now_width : obj.width(),
                            now_heigh : obj.height(),
                            width: newImg.width,
                            height: newImg.height
                        };
                        //计算缩放
                        if(imgWh.now_width != imgWh.width || imgWh.now_heigh != imgWh.height){

                            topLeft.top = Math.round((imgWh.now_heigh * topLeft.y)/imgWh.height) + topLeft.imgY;
                            topLeft.left = Math.round((imgWh.now_width * topLeft.x)/imgWh.width) + topLeft.imgX;

                        }

                        domCss(dom, url, wh, topLeft);
                    };
                };

            };

            //设置文字提醒,自适应缩放
            var setDomMsg = function(dom, topLeft, item){

                var domCss = function(dom, topLeft){
                    dom.css({
                        background: 'red',
                        width: null,
                        height: null,
                        top: topLeft.top + 'px',
                        left: topLeft.left + 'px'
                    });
                };

                var newImg = new Image();
                newImg.src = img.src;
                var imgWh = {}, obj = $(img);
                if(newImg.complete){
                    imgWh = {
                        now_width : obj.width(),
                        now_heigh : obj.height(),
                        width: newImg.width,
                        height: newImg.height
                    };
                    //计算缩放
                    if(imgWh.now_width != imgWh.width || imgWh.now_heigh != imgWh.height){

                        topLeft.top = Math.round((imgWh.now_heigh * topLeft.y)/imgWh.height) + topLeft.imgY;
                        topLeft.left = Math.round((imgWh.now_width * topLeft.x)/imgWh.width) + topLeft.imgX;

                    }

                    domCss(dom, topLeft);
                }else {
                    newImg.onload = function () {
                        imgWh = {
                            now_width : obj.width(),
                            now_heigh : obj.height(),
                            width: newImg.width,
                            height: newImg.height
                        };
                        //计算缩放
                        if(imgWh.now_width != imgWh.width || imgWh.now_heigh != imgWh.height){

                            topLeft.top = Math.round((imgWh.now_heigh * topLeft.y)/imgWh.height) + topLeft.imgY;
                            topLeft.left = Math.round((imgWh.now_width * topLeft.x)/imgWh.width) + topLeft.imgX;

                        }

                        domCss(dom, topLeft);
                    };
                };

                dom.unbind('click');
                dom.html(item.hover_message);   //文案提醒
                dom.show('normal');
            };

            //跳转页面
            var openWindow = function(url){
                if(url.indexOf('http') > -1){
                    window.open(url);
                }else{
                    window.open('http://' + url);
                }
            };

            //公共接口方法
            var app = (function() {
                var area = null;
                return {

                    setArea : function (arg){
                        area === null && arg.show();
                        area = arg;
                        return this;
                    },
                    getArea : function(){
                        return area;
                    },
                    addEvent : function(){
                        if(null != area){
                            area.eve = 0;
                        }
                        return this;
                    },
                    removeEvent : function(){
                        if(null != area){
                            area.eve = 1;
                        }
                        return this;
                    },
                    getId : function(){
                        if(null != area){
                            return area.id;
                        }
                        return null;
                    },
                    getEve : function(){
                        if(null != area){
                            return area.eve;
                        }
                        return null;
                    }
                }
            })();

            //热点区域
            var area = function(id, item){
                this.item = item;
                this.id = id;
                this.eve = 0;
                this.target = $('#' + id);
            };

            //热点msg
            area.prototype.show = function(){
                //console.log(this.id);
                //if(this.eve === 0){
                    var item = this.item;
                    var xy = imghotUtil.getAreaXY(item),
                        topLeft = {
                            x : xy.x,
                            y : xy.y,
                            imgX : imgX,
                            imgY : imgY,
                            top  : imgY + xy.y,
                            left : imgX + xy.x
                        };
                    switch(item.action_type) {
                        case 1 :   //图片提示
                            dom.html('');
                            if (imghotUtil.map.containsKey(item.hover_img)) {
                                var wh = imghotUtil.map.get(item.hover_img);
                                setDomImg(dom, item.hover_img, wh, topLeft);
                            } else {
                                var newImg = new Image();
                                newImg.src = item.hover_img;
                                if(newImg.complete){
                                    var wh = {
                                        width: newImg.width,
                                        height: newImg.height
                                    };

                                    imghotUtil.map.put(item.hover_img, wh);
                                    setDomImg(dom, item.hover_img, wh, topLeft);
                                }else{
                                    newImg.onload = function () {
                                        var wh = {
                                            width: newImg.width,
                                            height: newImg.height
                                        };

                                        imghotUtil.map.put(item.hover_img, wh);
                                        setDomImg(dom, item.hover_img, wh, topLeft);
                                    }
                                }
                            }
                            if(item.hover_img == "" || item.hover_img == null || item.hover_img == undefined){
                            	console.log($('#' + this.id))
                            	$('#' + this.id).css({
                                	'cursor' : 'pointer'
                                });
                            	$('#' + this.id).unbind('click').bind('click', function (e) {
                                    openWindow(item.click_link);
                                });
                            	
                            }

                            dom.unbind('click');                    //更保险,判断是否已经绑定易失效
                            dom.bind('click', function (e) {
                                openWindow(item.click_link);
                            });

                            dom.show();

                            break;
                        case 2 :    //文字提示
                            setDomMsg(dom, topLeft, item);

                            break;
                    };

                    this.eve = 1;
                //}
            };
            area.prototype.hide = function(){

            };
            area.prototype.addEvent = function(){
                this.target.bind('mouseover', function(){
                    app.event();
                });
                return this;
            };

            area.prototype.removeEvent = function(){
                this.target.unbind('mouseover');
            };

            //热点图
            var ImageHot = function(img, arr_info){
                this.unArea = null;
                this.events = [];
                this.target = img;
                this.arr_info = arr_info;
                this.areas = [];
            };

            ImageHot.prototype.initEreas = function(){
                for(var i = 0, len = arr_info.length; i < len ; i++){
                    var item = arr_info[i],
                        id = item.id,
                        _area = new area(id, item);
                    this.areas.push(_area);
                    imghotUtil.map.put(id, _area);
                };
                return this;
            };

            //计算热区缩放
            ImageHot.prototype.initZooming = function(){
                //调整MAP中坐标
                var adjustPosition = function (position, imgObj) {
                    var pageWidth = imgObj.now_width,
                        pageHeith = imgObj.now_heigh,   //图片当前尺寸

                        imageWidth = imgObj.width ,       //图片实际尺寸
                        imageHeigth = imgObj.height;

                    var each = position.split(",");
                    //获取每个坐标点
                    for (var i = 0; i < each.length; i++) {
                        each[i] = Math.round(parseInt(each[i]) * pageWidth / imageWidth);//x坐标
                        i++;
                        each[i] = Math.round(parseInt(each[i]) * pageHeith / imageHeigth);//y坐标
                    }
                    //生成新的坐标点
                    var newPosition = [];
                    for (var i = 0; i < each.length; i++) {
                        newPosition.push(each[i]);
                    }
                    return newPosition;
                };

                //矩形 多边形 圆形  缩放
                var zoomShap = function(area, imgWh){
                    var shap = area.target.attr('shape').toLowerCase();
                    if(shap === 'polygon' || shap === 'rect'){
                        var oldCoords = area.target.attr('coords');
                        var newcoords = adjustPosition(oldCoords, imgWh).join(',');
                        area.target.attr('coords', newcoords);
                    }else if(shap === 'circle'){
                        var oldCoords = area.target.attr('coords') + ',0';
                        var newcoords  = adjustPosition(oldCoords, imgWh);
                         newcoords.splice(3, 1);
                         area.target.attr('coords', newcoords);
                    }
                };

                var newImg = new Image();
                newImg.src = this.target.src;
                var imgWh = {},
                    obj = $(this.target),
                    areas = this.areas;
                if(newImg.complete){
                    imgWh = {
                        now_width : obj.width(),
                        now_heigh : obj.height(),
                        width: newImg.width,
                        height: newImg.height
                    };

                    if(imgWh.now_width != imgWh.width || imgWh.now_heigh != imgWh.height){
                        for(var i = 0, leng = areas.length; i < leng ;i++){
                            zoomShap(areas[i], imgWh);
                        }
                    }
                }else {
                    newImg.onload = function () {
                        imgWh = {
                            now_width : obj.width(),
                            now_heigh : obj.height(),
                            width: newImg.width,
                            height: newImg.height
                        };

                        if(imgWh.now_width != imgWh.width || imgWh.now_heigh != imgWh.height){
                            for(var i = 0, leng = areas.length; i < leng ;i++){
                                zoomShap(areas[i], imgWh);
                            }
                        }
                    };
                };
                return this;
            };

            ImageHot.prototype.addEvents = function(){
                for(var i = 0, len = this.areas.length; i < len ; i++){
                    this.areas[i].target.bind('mouseover', function(e){
                        var id = e.target.id;
                        var _area = imghotUtil.map.get(id);
                        //if(app.getId() != _area.id){
                            _area.show();

                        //};
                        //app.addEvent();
                        //app.setArea(_area).removeEvent();
                    });
                }

                return this;
            };
            //设定图片事件
            ImageHot.prototype.addImgEvents = function(){
          	 $(this.target).hover(function(){
               	try{
               		var div=$('#' + imghotUtil.msg.msgid);
                       div.show();
               	}catch(e){}
               },function(){
               	try{
               		var div=$('#' + imghotUtil.msg.msgid);
                       div.hide();
               	}catch(e){}
               });
              return this;
            };

            this.imgs.push((new ImageHot(img, arr_info)).initEreas().initZooming().addEvents().addImgEvents());  //this.imgs 为备用
        }
    };

    var isPreviewUrl=window.location.href.indexOf('pc=1')>0;
    var isPreview = 0;
    if(isPreviewUrl){
    	isPreview = 1;
    }
    imghotUtil.initImg().initArea();

})(jQuery, window)});
js,刷新价格 js刷新
define([ '$','MtAjax'],
  function ($,MtAjax) {
    'use strict';

    function getPriceAndStock(){
      var that = this;
      var ajaxURL = window.SERVER_URL + '/mobile/cmsShow/batchGetSkuPriceAndStock.htm';
      var objJson = [];
      //获取页面class为skuinfo的数据,更新该数据的价格和库存信息
      $('.skuinfo').each(function(){
        var info = {};
        var sku = $(this).attr('data-id');
        var topicId = $(this).attr('data-topicId');
        info.sku = sku;
        info.topicId = topicId;
        objJson.push(info);
      });
      if(objJson == null || objJson.length <= 0){//页面没有活动商品,直接返回
        return;
      }
      var params = {
        requestBody: {
          itemDetailTos:objJson
        },
        callback: function (response) {
          var code = response.rescode.code;
          if(code == "0"){ //读取接口成功
            var resultData = response.data;
            //如果活动商品没有查询到价格库存信息或者活动结束,如何处理?
            if(resultData == null || resultData.length <= 0){
              return;
            }
            for(var key in resultData){
              var itemDetaiInfo = resultData[key];
              var sku = itemDetaiInfo.sku;
              var topicId = itemDetaiInfo.topicId;
              if(itemDetaiInfo.status == 0){//活动商品有效且进行中,更新页面价格和库存
                var price = itemDetaiInfo.price;//促销价
                var oldPrice = itemDetaiInfo.oldPrice;//原价
                //价格显示防呆,如果促销价大于等于原件,则促销价等于原价,且只显示促销价
                if(Number(price) >= Number(oldPrice)){
                  $('#'+key).find('.price').html(oldPrice+'<span class="sale"></span>');
                }else {
                  $('#'+key).find('.price').html(price+'<s class="slice">'+oldPrice+'</s>');
                }
              }else{//活动商品无库存或结束或无效,该怎么处理??
                // Todo:
              }
            }

          }else{//接口处理查询处理失败
            //Todo:
          }

        }
      };
      MtAjax.ajax(ajaxURL, params, 'post');
    }

    return {
      'getPriceAndStock': getPriceAndStock
    };
  });
静态文件压缩 文件压缩
package com.newheight.global.util;

import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.mozilla.javascript.ErrorReporter;
import org.mozilla.javascript.EvaluatorException;

import com.yahoo.platform.yui.compressor.CssCompressor;
import com.yahoo.platform.yui.compressor.JavaScriptCompressor;

/**
 * js压缩工具(yuicompressor)
 * 
 * 2015-2-26
 * @author weiqingjian
 */
public class CompressorUtils {
	
	private static Logger logger = Logger.getLogger(CompressorUtils.class);
	
	/**
	 * 压缩指定js内容
	 * @param jsText
	 * @return
	 */
	public static String compressJs(String jsText) {
		if (StringUtils.isEmpty(jsText)) {
			return "";
		}
		Reader in = null;
        Writer out = null;
		try {

			in = new StringReader(jsText);
			out = new StringWriter();
			
			JavaScriptCompressor compressor = new JavaScriptCompressor(in, new ErrorReporter() {

                public void warning(String message, String sourceName,
                        int line, String lineSource, int lineOffset) {
                    logger.error("\n[WARNING]:");
                    if (line < 0) {
                        logger.error("  " + message);
                    } else {
                        logger.error("  " + line + ':' + lineOffset + ':' + message);
                    }
                }

                public void error(String message, String sourceName,
                        int line, String lineSource, int lineOffset) {
                    logger.error("[ERROR]:");
                    if (line < 0) {
                        logger.error("  " + message);
                    } else {
                        logger.error("  " + line + ':' + lineOffset + ':' + message);
                    }
                }

                public EvaluatorException runtimeError(String message, String sourceName,
                        int line, String lineSource, int lineOffset) {
                    error(message, sourceName, line, lineSource, lineOffset);
                    return new EvaluatorException(message);
                }
            });
			
            int linebreakpos = -1;	//指定换行的列
            boolean munge = true;	//混淆
            boolean verbose = false;	//显示info和warn级别的信息 
            boolean preserveAllSemiColons = false;	//保留分号
            boolean disableOptimizations = false;	//禁止优化
            compressor.compress(out, linebreakpos, munge, verbose, preserveAllSemiColons, disableOptimizations);

            //返回压缩后的js内容
            return  out.toString();
        } catch (Exception e) {
        	logger.error("Compress js error!", e);
        } finally {
        	try {
        		if (in!=null) {
        			in.close();
        		}
        	} catch (Exception ex) {
        		//ignore
        	}
        	try {
        		if (out!=null) {
        			out.close();
        		}
        	} catch (Exception ex) {
        		//ignore
        	}
        }

		return jsText;
	}
	
	
	
	
	/**
	 * 对css文本压缩,当文本长度小于20时不压缩,原样返回
	 * @param in
	 * @return
	 * updated by chenkaiqiang, 2014-7-14
	 */
	public static String compressCss(String in){
		if(in == null || in.length() < 20){
			return in;
		}
		StringWriter writer = null;
		StringReader reader = null;
		try {
			reader = new StringReader(in);
			CssCompressor compresser = new CssCompressor(reader);
			writer = new StringWriter();
			compresser.compress(writer, 50);
			writer.flush();
			String ret =  writer.toString();
			if(!ret.endsWith("}")){
				logger.error("Compress css error! not end with }");
				ret = in;//压缩错误
			}
			return ret;
		} catch (Exception e) {
			logger.error("Compress css error!", e);
		}finally{
			try {
        		if (reader!=null) {
        			reader.close();
        		}
        	} catch (Exception ex) {
        		//ignore
        	}
			try {
        		if (writer!=null) {
        			writer.close();
        		}
        	} catch (Exception ex) {
        		//ignore
        	}
		}
		return in;
	}
	
	
}
查看类是否有默认构造器 构造器
package com.meitun.hitaoorder.service.impl;

import java.io.File;
import java.io.FileFilter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Serializable;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath*:spring.xml" })
public class TestGetNoConstructorClassess {
	@Test
	public void test(){
		
		List<Class> classes=getClasssFromPackage("com.meitun");
		for(int i=0;i<classes.size();i++){
			if(isNeedFilterClass(classes.get(i))){
				continue;
			}
			try {
				classes.get(i).newInstance();
			} catch (Exception e) {
				append2File("============ 类:"+classes.get(i).getName()+"\n");
			}
		}
	}
	
	void append2File(String str){
		FileWriter writer =null;
		try {
			writer= new FileWriter("D:/ooo.txt", true);
            writer.write(str);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(writer!=null){
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private boolean isNeedFilterClass(Class cls) {
		//接口,枚举类,没有实现Serializable接口的类,排除
		if(cls.isInterface()||cls.isEnum()||(!Serializable.class.isAssignableFrom(cls))){
			return true;
		}
		return false;
	}


	/** 
	 * 获得包下面的所有的class 
	 *  
	 * @param pack 
	 *            package完整名称 
	 * @return List包含所有class的实例 
	 */  
	public static List<Class> getClasssFromPackage(String pack) {  
	    List<Class> clazzs = new ArrayList<Class>();  
	  
	    // 是否循环搜索子包  
	    boolean recursive = true;  
	  
	    // 包名字  
	    String packageName = pack;  
	    // 包名对应的路径名称  
	    String packageDirName = packageName.replace('.', '/');  
	  
	    Enumeration<URL> dirs;  
	  
	    try {  
	        dirs = Thread.currentThread().getContextClassLoader().getResources(packageDirName);  
	        while (dirs.hasMoreElements()) {  
	            URL url = dirs.nextElement();  
	  
	            String protocol = url.getProtocol();  
	  
	            if ("file".equals(protocol)) {  
	                String filePath = URLDecoder.decode(url.getFile(), "UTF-8");  
	                findClassInPackageByFile(packageName, filePath, recursive, clazzs);  
	            }
	        }  
	  
	    } catch (Exception e) {  
	        e.printStackTrace();  
	    }  
	  
	    return clazzs;  
	}  
	  
	/** 
	 * 在package对应的路径下找到所有的class 
	 *  
	 * @param packageName 
	 *            package名称 
	 * @param filePath 
	 *            package对应的路径 
	 * @param recursive 
	 *            是否查找子package 
	 * @param clazzs 
	 *            找到class以后存放的集合 
	 */  
	public static void findClassInPackageByFile(String packageName, String filePath, final boolean recursive, List<Class> clazzs) {  
	    File dir = new File(filePath);  
	    if (!dir.exists() || !dir.isDirectory()) {  
	        return;  
	    }  
	    // 在给定的目录下找到所有的文件,并且进行条件过滤  
	    File[] dirFiles = dir.listFiles(new FileFilter() {  
	        @Override  
	        public boolean accept(File file) {  
	            boolean acceptDir = recursive && file.isDirectory();// 接受dir目录  
	            boolean acceptClass = file.getName().endsWith("class");// 接受class文件  
	            return acceptDir || acceptClass;  
	        }  
	    });  
	  
	    for (File file : dirFiles) {  
	        if (file.isDirectory()) {  
	            findClassInPackageByFile(packageName + "." + file.getName(), file.getAbsolutePath(), recursive, clazzs);  
	        } else {  
	            String className = file.getName().substring(0, file.getName().length() - 6);  
	            try {  
	                clazzs.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + "." + className));  
	            } catch (Exception e) {  
	                e.printStackTrace();  
	            }  
	        }  
	    }  
	}
}
Global site tag (gtag.js) - Google Analytics