interview challenge 1
by fangunxs
HTML
<div class="delivery-truck"></div>
<div class="depot">
<span class="parcel"></span>
<span class="parcel"></span>
<span class="parcel"></span>
</div>
<div id="house" class="delivery-address"></div>
<div id="office" class="delivery-address"></div>
<div id="factory" class="delivery-address"></div>
CSS
body{
background:#000;
}
.delivery-truck{
background:#CC0000;
width:30px;
height:30px;
position:absolute;
z-index: 1;
}
.depot{
position:absolute;
width:150px;
height:150px;
background:#ccc;
border:3px dashed #666;
top:200px;
left:300px;
}
.delivery-address{
position:absolute;
border:3px dashed yellow;
}
.parcel{
width:5px;
height:5px;
background:white;
display:block;
border:2px solid red;
}
#house{
width:50px;
height:50px;
top:340px;
left:700px;
background:#663300;
}
#office{
width:80px;
height:150px;
top:100px;
left:650px;
background:white;
}
#factory{
width:160px;
height:60px;
top:500px;
left:600px;
background:grey;
}
JavaScript
jQuery(function( $ ){
var address_book = new Array();
getAddress('depot',address_book);
getAddress('delivery-address',address_book);
var n = 0;
function getAddress(cls,address){
var target_address = $('.'+cls);
for(var i=0; i<target_address.length; ++i){
address_book.push($(target_address[i]).offset());
address_book[address_book.length-1]['type'] = cls;
console.log($(target_address[i]).attr('id'));
if($(target_address[i]).attr('id')){
address_book[address_book.length-1]['id'] = $(target_address[i]).attr('id');
}
}
};
function track(dom,i){
if(i<address_book.length){
$(dom).animate({
left: address_book[i].left,
top: address_book[i].top
},1000,function(){
if(address_book[i]['type'] === 'depot'){
loadItem();
} else {
unloadItem(address_book[i].id);
}
++i;
track(dom,i);
});
}else{ //finish deliver
$(dom).animate({
left: '+=50',
},1000,function(){
});
}
};
function loadItem(){
$('.delivery-truck').append($('.parcel'));
}
function unloadItem(id){
var parcels = $('.delivery-truck .parcel');
if(parcels.length){
$('#'+id).append($(parcels)[0]);
}
}
$('.delivery-truck').click(function(){track(this,n)});
});