product.js 2.4 KB
/**
 *Description: 商品列表页
 *Author: chenglong.wang@yoho.cn
 *Date: 2015/12/2
 */

var $ = require('yoho.jquery'),
    productEvent = require('../common/product-event');

var $goodsContainer = $('.goods-container'),
    $goodItem = $goodsContainer.find('.good-info'),
    $goodItemWrapper = $goodsContainer.find('.good-item-wrapper'),
    $goodInfoMain = $goodsContainer.find('.good-info-main'),
    $goodSelectColor = $goodsContainer.find('.good-select-color');

var MouseOver = productEvent($goodItem, 5);

// 构造html
function createColorList(data) {
    var colorListStr = '',
        len = data.length,
        row = 4, //每列ul放4个li
        col = Math.ceil(len / row), //需要几**列**ul
        i,
        j,
        index,
        ulNum = 0;

    for (i = 0; i < col; i++) {
        colorListStr += '<ul>';
        for (j = 0; j < row; j++) {
            index = i * row + j;
            if (index === len) {
                break;
            }
            colorListStr +=
                '<li>' +
                '<a href="' + data[i * row + j].url + '">' +
                '<img src="' + data[i * row + j].src + '" />' +
                '</a>' +
                '</li>';

            if (j === row - 1) {
                colorListStr += '</ul>';
                ulNum++;
            }
        }
    }
    if (ulNum < col) {
        colorListStr += '</ul>';
    }
    return colorListStr;
}

MouseOver.addHandler('MouseEnter', function(event) {

    var itemMr = 10, //list的右边距
        itemMb = 35, //list的下边距
        wrapperX = (event.targetX - 1) * (event.targetWidth + itemMr) - 21,
        wrapperY = (event.targetY - 1) * (event.targetHeight + itemMb) + 25 - 19;

    $goodInfoMain.html('');
    $goodSelectColor.html('');
    $goodItemWrapper.css({
        display: 'none'
    });
    $.ajax({
        type: 'GET',
        url: '/product/index/productColor',
        dataType: 'json'
    }).then(function(data) {

        $goodInfoMain.append(event.targetDuplicate);
        $goodSelectColor.append($(createColorList(data)));
    });

    $goodItemWrapper.css({
        left: wrapperX,
        top: wrapperY,
        display: 'inline-block'
    });
});

$goodItemWrapper.mouseleave(function() {
    $goodInfoMain.html('');
    $goodSelectColor.html('');
    $goodItemWrapper.css({
        display: 'none'
    });
});