minidisplay.js 16.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
/* 
 * 列表页中mini价格窗口控制函数 
 * Code at 2014/11/3   
 * by van
 */
 
define( 'minidisplay' ,function( require, exports, module ){

	var minidisplay = function( options ){
		this.o = {
            selector: 'list-goods-hover', //防止迷你价格窗口的容器名称
			range: 'hover-range', //最外层定位元素
			frame: 'hover-frame', //显示框体元素
			content: 'hover-content', //包含价格内容元素
			btn: 'hover-btn', //控制不同价格列表显示按钮容器
			widthLi: 230, //包含迷你价格窗口的列表元素宽度
			offset: 700, //垂直偏移量,通过判断控制右侧价格窗口不超过列表容器
			symbol: ',', //分隔符
			leftbtn: 'btnleft', //左移按钮名
			rightbtn: 'btnright', //右移按钮名
			index: 'pic-index', //包含窗口index容器名
            contrary: 'hover-contrary', //价格窗口接触浏览器顶部,在列表下方显示窗口
            shadowArrow: 'shadow-arrow',
            domain: '../guige.json?', //获取返回数据的对应域名
            dataurl: 'data-url', //自定义属性用于放置对应数据的ajax请求路径
            param: 'pid',
			jsonName: ["priceInfo","quotationType","saleUnit"],
            moneyFormat: function( input ){
                return input;
            }
		};
		
        this.o = $.extend( this.o, options );
        this.target = $( _name( this.o.selector ) );
        this.errorinfo = false;

        this.init( this.target );
        this.imgListener();
	};
    minidisplay.prototype = {
        init: function( target ){
            var _this = this;

            target.each( function(){
                _this.hoverListener( this );
            } );
        },
        check: function( target ){
            //检测价格窗口是否为空
            var children = $(target).has( $(_name(this.o.content, "div")) );

            return children = (children.length >0) ? true : false;
        },
        show: function( target ){
            $(target).find(_name(this.o.range)).show().css( 'visibility', 'visible' );
            $(target).find(_name(this.o.shadowArrow)).css({ visibility: 'visible' });
			if ( $(target).parent().parent().offset().top + 30
					< $(document).scrollTop() )
			{
			$(target).find(_name(this.o.shadowArrow))
                .css({ visibility: 'hidden' });
			}
        },
        hide: function( target ){
            $(target).find(_name(this.o.range)).css( 'visibility', 'hidden' );
            $(target).find(_name(this.o.shadowArrow)).css( 'visibility', 'hidden' ); 
        },
        displayLoading: function( target ){
            $(target).find( _name(this.o.content) ).css({
                background: "none"
            })
        },
        ajax: function( target, url ){
            //发送异步请求获取数据
            //依据回返状态进行不同操作
            var _this = this, cache;

            $.ajax({
                type: "get",
                url: url,
                dataType: "json",
                success: function( data ){
                    setTimeout( function(){
                        cache = _this.makeHtml( target, data );
                        _this.controller( target, cache );
                    }, 100 );
                },
                error: function(){
                    _this.errorinfo = true;
                    setTimeout( function(){
                        _this.makeLast( target );
						_this.locateError( target );
                    }, 500 );
                }
            })
        },
        makeLast: function( target ){
            //当发送请求失败时显示内容
            $(target).find( _name(this.o.content) )
                .append(
                    '<span class="get-error">网络好像不太给力</span>'
                    )
                .css({
                background: "url(http://static.nong12.com/static/newStatic/pnr/images/receipt_on.png) no-repeat 15px center",
				width: 160,
				height: 100
            });
        },
        makeRange: function( target, data ){
            //创建迷你价格窗口框体
            if ( $(target).find(_name(this.o.range)).length >= 1 ){
                return false;
            }
            var html = '<div class="'+ this.o.range +'">'+
	                    '<div class="'+ this.o.frame +'">'+
                            '<div class="'+ this.o.content +' clearfix">'+
                            '</div>'+
                        '</div>'+
                        '<div class="'+ this.o.btn +'">'+
							'<span class="'+ this.o.leftbtn +'"></span>'+
								'<div class="'+ this.o.index +'">'+
								'</div>'+
							'<span class="'+ this.o.rightbtn +'"></span>'+
						'</div>'+
	                    '<i></i> <em></em>'+
	                    '<i class="'+ this.o.shadowArrow +'"></i>'+
                        '</div>';

            $(html).appendTo( $(target) );
            this.show( target );
        },
        makeHtml: function( target, data ){
            //创建迷你价格窗口内容
            var html = '',  cell = '', index = '', make,
            info = data[this.o.jsonName[0]],
			unit = data[this.o.jsonName[2]],
            indexarea = $(target).find( _name(this.o.index) ),
            content = $(target).find( _name(this.o.content) );
	
			if ( typeof info == "undefined" && info.length == 0 ){
				return false;
			}
		
			if ( data[this.o.jsonName[1]] == 1 ){
				make = this.makeCell();
			}else {
				make = this.makeOtherCell();
			}

            for (var k=0, l = Math.ceil( info.length/5 ); k< l;k++){
                cell += '<div><table border=0 cellspacing=0 cellpadding=0>';
                for (var i = 0, n = info.length; i< n; i++){
                    cell += "<tr>" + make( info.pop(), unit ) + "</tr>";
                    if ( i != 0 && i%4 === 0 ){ break };
                }
                cell += '</table></div>';
            }
            index = '<b class="on"></b>';
            for (var i = 0; i< k-1; i++){
                index += " <b></b> ";
            }

            $(cell).appendTo( content );
            $(index).appendTo( indexarea );
            this.showFirst( target );
            return this.set( target, 0 );
        },
        showFirst: function( target ){
            //防止初始状态中无元素显示
            //将迷你价格窗口中第一个内容元素设置为显示状态
            $(target).find( _name(this.o.content,"div") ).eq(0).addClass("on");
        },
        set: function( target, index ){
            //设置迷你价格窗口属性
            var _this = this, i = index,
                carve = _this.getCarve( target ),
                length = carve.length;
            if ( length === 0 ){ return false; };
    
            var arr = carve[i].split(_this.o.symbol);

		    _this.carve( target, {
			    width: arr[0], //不同价格table宽度
			    height: arr[1], //高度
			    length: carve.length //价格table包含的数量
		    });
		    _this.locate( target, {
                data: [
				    arr[0], //不同价格table宽度
				    arr[1], //高度
				    carve.length //价格table包含的数量
                ]
		    } );

            return carve;
        },
        imgListener: function(){
            //监听图片链接
            //同步发送ajax请求和操作迷你窗口
            $( ".goods-img" ).live({
                mouseenter: function( event ){
                    $(this).parent().find(".goods-price").trigger("mouseenter");
                },
                mouseleave: function(){
                    $(this).parent().find(".goods-price").trigger("mouseleave");
                }
            })
        },
        hoverListener: function( target ){
            //初始状态监听事件 
            //判断是否发送ajax请求数据
            var _this = this, clock, url;

            $(target).live({
                mouseenter: function(){
                    clearTimeout( clock );
                    clock = setTimeout( function(){
                    if (_this.check( target )){
                        _this.show( target );
                    }else {
                        if ( $(target).find(_name(_this.o.range)).length >= 1 )
                        {
                            return false;
                        }
                        _this.makeRange( target );
		                _this.locateInit( target );
						url = _this.o.domain + _this.o.param + "=" + $(target).attr( _this.o.dataurl );

                        _this.ajax( target, url );
                    };
                    }, 400 );
                },
                mouseleave: function(){
                    clearTimeout( clock );
                    clock = setTimeout( function(){
                        _this.hide( target );
                        if ( _this.errorinfo ){
                            $( target ).find( _name(_this.o.range) ).remove();
                            _this.errorinfo = false;
                        }
                    }, 100 );
                } 
            });
        },
        controller: function( target, arr ){
            //迷你窗口控制器事件监听
            var _this = this, i = 0, clock,
            carve = arr, length = carve.length;
            //左按钮
			$(target).find(  _name( _this.o.leftbtn ) )
			.live({
				click: function(){
                    --i;
                    if ( i < 0 ){
                        i += length;
                    }

					_switcher();
				}
			});
            //右按钮
			$(target).find(  _name( _this.o.rightbtn ) )
			.live({
				click: function(){
					++i;
                    i = i % length;
					
					_switcher();
				}
			});
            //索引点击事件
			$(target).find(  _name( _this.o.index,"b" ) )
			.live({
				click: function(){
					if ( i != $(this).index() ){
						i = $(this).index();
					}else{ return false };
					
					_switcher();
				}
			});
			$(target).live({
				mouseenter: function(){
					if ( typeof carve[i] == "undefined" ){
						return false;
					}
				
					var $_this = $(this),
                    arr = carve[i].split(_this.o.symbol);
            
			        _this.carve( target, {
					    width: arr[0], //不同价格table宽度
					    height: arr[1], //高度
					    length: carve.length //价格table包含的数量
			        });

			        _this.locate( target, {
                        data: [
					        arr[0], //不同价格table宽度
					        arr[1], //高度
					        carve.length //价格table包含的数量
                        ]
			        } );
				}
			});

			function _switcher(){
                //依据index的值不同显示对应的价格
				//切换不同价格。
                var arr = carve[i].split(_this.o.symbol);
				_this.switcher( target, {
					rank: i, //显示价格table的索引值
					width: arr[0], //不同价格table宽度
					height: arr[1], //高度
					length: carve.length //价格table包含的数量
				});
			};
        },
		locateError: function( target ){
			this.locate( target, {
				data: [ 160, 100, 1 ]
			} );
		},
		locateInit: function( target ){
			this.locate( target, {
				data: [ 106, 50, 1 ]
			} );
		},
		locate: function( target,value ){
			//定位价格显示窗口位置
			var posLeft = 0, offset = 10,
			li = $(target).parent().parent(),
			frame = $(target).find(  _name( this.o.frame ) ),
			content = $(target).find(  _name( this.o.content ) ),
			btn = $(target).find(  _name( this.o.btn ) ),
			i = $(target).find("i"),
			carve = value.data;

            //通过迷你窗口内容宽度设置不同对齐方式
			posLeft = i.position().left - parseInt(carve[0])/2 - offset/2;
			//判断是否触及可视区域左侧
			if ( $(target).offset().left < 30 ){
				posLeft = 10;
			}
			//判断是否触及可视区域右侧
			if ( $(window).width() - li.offset().left - li.width() < 100 ){
				posLeft = 2*i.position().left - parseInt(carve[0]) - 2*offset;
			}
            this.isTouchtop( target, {
                length: carve[2],
                frame: frame,
                content: content,
                btn: btn
            } );

			frame.css({
				left: posLeft
			});
			btn.css({
				left: Math.ceil(i.position().left - btn.width()/2 + offset/2)
			});
		},
		getCarve: function( target ){
			//获取初始化显示区域数据
			
			var divs = $(target).find( _name( this.o.content,"div" )),
			arr = [];
			for ( var i=0;i < divs.length;i++ ){
				arr[i] = divs.eq(i).width()+ 
						this.o.symbol 
						+divs.eq(i).height();
			};
					
			return arr;
		},
		carve: function( target, value ){
			//切割显示内容框体宽度,高度。
			
			var btn = $(target).find(  _name( this.o.btn ) );

			$(target).find(  _name( this.o.content ) ).css({
				width: value.width,
				height: value.height 
			});
		},
		showPoint: function( target,len ){
			//判断是否具有多个价格table,显示index容器。
		
			var btn = $(target).find(  _name( this.o.btn ) );

			if ( parseInt(len) > 1 ){
				return  parseInt(btn.height());
			}
			return 0;
		},
        isTouchtop: function( target,value ){
            //判断mini-frame 是否触及web-frame顶部
            var point = this.showPoint( target, value.length );
            //判断列表父元素相对浏览器顶部的偏移值是否大于滚动条
            if ( $(target).parent().parent().offset().top + 30
                    > $(document).scrollTop() )
            {
                //大于滚动条值时则将迷你价格窗口箭头指向下方
                value.frame.parent().removeClass( this.o.contrary );
                value.frame.attr( 
                    "style",
                    "bottom:10px"
                );
                value.content.css( {
                    marginTop: 0,
                    marginBottom: point 
                } );
                if ( point ){
                    value.btn.attr( "style","bottom:10px" );
                }else {
                    value.btn.hide();
                }
            }else {
                //小于滚动条值时则将迷你价格窗口箭头指向上方
                value.frame.parent()
                    .removeClass( this.o.contrary )
                    .addClass( this.o.contrary )
                value.frame.attr( 
                    "style",
                    "top:35px"
                );
                value.content.css( {
                    marginBottom: 0,
                    marginTop: point 
                } );
                if ( point ){
                    value.btn.attr( "style","top:42px" );
                }else {
                    value.btn.hide();
                }
            }
        },
		switcher: function( target, obj ){
			//切换不同价格table函数。
			
			var divs = $(target).find(  _name( this.o.content,"div" ) );
			
			indexs = $(target).find(  _name( this.o.index,"b" ) );
			//Set data suit the ContentTable.
			this.carve( target, {
				width: obj.width,
				height: obj.height,
				length: obj.length
			})
			this.locate( target, {
				data: [ obj.width,obj.height,obj.length ]
			});
			//Show the ContentTable which had selected.
			divs.removeClass("on").hide();
			divs.eq( obj.rank ).addClass("on").show(150);
			//Set the picture index 
			indexs.removeClass("on");
			indexs.eq( obj.rank ).addClass("on");
		},
        makeCell: function(){
            //返回只有两种属性的价格窗口内容
            var _this = this;

            return function( info, unit ){
                var cache = "<td>¥"+ _this.o.moneyFormat( info["price"] ) +"</td>";

		        for (var i=0, len=info["attrs"].length; i< len; i++){
			        cache += "<td><b>"+ info["attrs"][i] + "</b></td>";
		        };

                return cache;

            };
        },
        makeOtherCell: function(){
            //返回有多种属性的价格窗口内容
            var _this = this;

            return function( info, unit ){
		        var html,
			        cache = "<td>¥"+ _this.o.moneyFormat( info["price"] ) +"</td>";

		        html = info["minPurchaseScope"] + "-" + info["maxPurchaseScope"] + unit;
		        if ( typeof info["maxPurchaseScope"] == "undefined" ){
			        html = info["minPurchaseScope"] + unit + "以上";
		        }
		
		        cache += "<td><b>"+ html + "</b></td>";
				
		        return cache;
            
            };
        }
    }
	
	function _name( name, child ){
		if ( typeof child == "string" ){
			return (
				name.replace(/^/, ".").replace(/$/, " ") + child
			)
		};
		return name.replace(/^/, ".");
	};
	
	return minidisplay;
	
});