Показать сообщение отдельно
  #12 (permalink)  
Старый 03.09.2015, 14:10
Аватар для Lemme
Профессор
Отправить личное сообщение для Lemme Посмотреть профиль Найти все сообщения от Lemme
 
Регистрация: 15.07.2015
Сообщений: 511

jQuery ваще не знаю, поэтому перепишешь правильно =).
function adjacentItems(index){
    var $parent = $('.wrapper'),
        $child = $('.child');
    
    var count = $child.length;
    
    // сколько элементов в линии
    var xItems = Math.floor($parent.width() / $child.width());
    
    // шаг вправо
	var $right = null,
        right = index + 1;
    
    if (right <= count && right % xItems !== 0) {
    	$right = $child.eq(right)
    }
    
    // шаг влево
	var $left = null,
        left = index - 1;
    
    if (left >= 0 && index % xItems !== 0) {
    	$left = $child.eq(left)
    }
    
    // шаг вверх
	var $top = null,
        top = index - xItems;
    
    if (top >= 0 && index % xItems !== 0) {
    	$top = $child.eq(top)
    }
    
    // шаг вниз
	var $bottom = null,
        bottom = index + xItems;
    
    if (bottom <= count && bottom - 1 % xItems !== 0) {
    	$bottom = $child.eq(bottom)
    }
    
    // массив элементов
    var data = [];
    
    // собственно, если он есть, то записываем в массив.
    if ($right) {
    	data.push($right);
    }
    if ($left) {
    	data.push($left);
    }
    if ($top) {
    	data.push($top);
    }
    if (bottom) {
    	data.push($bottom);
    }
    return data;
}

$('.wrapper').on('click', '.child', function() {
        // получаем список эелемнтов
	var $items = adjacentItems($(this).index());
    // перебираем массив
    $items.forEach(function($item){
    	$item.css('background', 'yellow');
    });
});


p.s я тут убрал ввод с prompt, добавишь.
http://jsfiddle.net/73gLc3ap/4/

p.s А почему не сделаешь используя матрицу? Я про

data[x][y]


Было бы проще искать элемементы

Последний раз редактировалось Lemme, 03.09.2015 в 15:01.
Ответить с цитированием