2012-06-11 19 views
0

На прошлой неделе у меня был очень полезный ответ о том, как создать этот скрипт, который отлично работает, за исключением одной небольшой проблемы. Проще всего объяснить с помощью визуальной помощи http://avalon.eaw.com/#finisheschange backgroundPosition на основе текущего backgroundPosition

Это свойство использует свойство backgroundPosition для изменения цвета. единственная проблема заключается в том, что опции «звуковой сигнал» жестко закодированы таким образом, что если вы в настоящее время просматриваете динамик, у которого есть белая кабина с цветным рогом и хотите изменить шкаф на черный, он также меняет рожок на черный. в настоящее время нет возможности просматривать черную кабину с цветным рогом.

Чтобы исправить это, мне нужно сделать условное заявление, но я не уверен, как заставить его работать. что-то вроде

function colorChange() { 
    // Use xposition and yposition which are changed by JS function above 
    $("#target").css('background-position', xposition+'px '+yposition+'px'); 
    if$("#target").css('background-position') == {x:-754} 
     updatePositions({x:-377}); 
    if$("#target").css('background-position') == {x:-377} 
     updatePositions({x:-754}); 
} 

////// EDIT /////// модератор просто удалил последующие меры по этой проблеме я писал в порядке, чтобы попытаться помочь найти ответ. спасибо за подавление любой возможной помощи модератора mr! Я все больше расстраиваюсь этим форумом. во всяком случае, я поставил его ниже, надеясь, что кто-то поможет найти решение.

хорошо у меня есть ответ, который НЕ работает, но, надеюсь, он поможет кому-то найти тот, который работает. после того, как делать еще некоторое чтение на Jquery стенографии я попытался сделать отдельную функцию только для шкафа-пиано образчика:

function colorChangePiano() { 
    var bp = $("background-position").css; 
    $("#target").css("background-position", (bp = {x:-1131}) ? "{x:-377}" : "{x:0}"); 
} 

я знаю, что есть что-то не так с самим синтаксисом, но большая проблема в том, что он не впросак к функция, которая управляет остальной части образчики:

// variable outside of function() scope 
var xposition, 
    yposition; 

// Update values of xposition and or yposition 
function updatePositions(axes) { 
    // Check to see which axis was passed in x, y or both, then update values 
    if (typeof(axes.x) !== 'undefined') xposition = axes.x; 
    if (typeof(axes.y) !== 'undefined') yposition = axes.y; 

    //Call function to actually move BG image 
    colorChange(); 
} 

// Function move BG image, using variables declared above 
function colorChange() { 
    // Use xposition and yposition which are changed by JS function above 
    $("#target").css('background-position', xposition+'px '+yposition+'px'); 
} 

ради того, чтобы быть до конца, вот несколько примеров HTML вызовов:

<a href="#" onclick="updatePositions({x:-1131})"><img src="/images/cabinets/swatches/swatch-siren.jpg" /><p>siren</p></a> 
<a href="#machine" onclick="updatePositions({y:-999})"><img src="/images/cabinets/swatches/swatch-machine.jpg" /><p>machine</p> 
<a href="#" onclick="updatePositions({x:-754})"><img src="/images/cabinets/swatches/swatch-polar.jpg" /><p>polar</p></a></a> 
<a href="#" onclick="updatePositions({x:0})"><img src="/images/cabinets/swatches/swatch-piano.jpg" /><p>piano</p></a> 

этот сайт должен пойти сегодня вечером, и я начинаю немного волноваться. есть ли у кого-нибудь какое-либо понимание?

+0

Кто-нибудь там? –

+0

Я думаю, что некоторые из нас читают это и волнуются. Похоже, что в коде есть избыток для результата, который он должен доставить. Если я нахожу что-то непонятное, кроме надежды, я обычно переписываю его. Вот что я вам рекомендую. Повторите код, чтобы его легче было понять и работать, поскольку появляются будущие изменения.Извините, но это лучший ответ, который я могу дать. – kevin628

+0

lol наилучшим образом спасибо для отвечать хотя бы. Я все еще удивлен, что нет простого способа проверить положение фона и обновить ось на основе этого. –

ответ

0

Благодаря моему хорошему (и очень умному) другу Эли Хантингтону есть ответ - хотя и очень сложный. Вот ссылка на рабочий сайт и фрагменты кода, которые относятся к этому вопросу. Надеюсь, это помогает другой бедной душе. Здесь есть связанная с этим тема (jquery background change one axis only) с гораздо более простым вопросом, на который я надеюсь получить ответ. Там только имеет, чтобы быть более простым способом сделать это.

сайт: http://avalon.eaw.com/

сценарий: (finishScroll и finishScroll2 являются localScroll функция плагин не имеет отношения к этому конкретному вопросу)

// FINISHES SCRIPT // 
// Make an object to hold various information about the application 
finishes = { 

cabinets: { // Columns 
    colors: ['polar', 'piano'], // Add new cabinet colors here 

    /* 
    * New cabinet colors are represented in columns and can be 
    * added to the sprite to the right edge. 
    * After adding two new columns to the Sprite 
    * add the following after polar_custom: '-1131px' (don't forget comma): 
    * 
    *  anycolor_standard: '-1508px' //(i'm guessing) 
    *  anycolor_custom: '-1885px' //(also guessing) 
    * 
    */ 
    piano_standard : '0px', // Column where horn matches grill 
    piano_custom : '-377px', // Column where horn is custom color 
    polar_standard : '-754px', 
    polar_custom : '-1131px' 
}, 
colors: { // Rows 
    // New colors can be added to the sprite at the bottom and then added last here with the position (from the sprite) 
    siren:  '0px', 
    medallion: '-333px', 
    starlight: '-666px', 
    machine: '-999px' 
}, 
current_cabinet_color: 'piano', // Will be updated by click events to updateCabinet 
current_grille_color: 'siren', // Will be udpated by click events to updateCabinet 
current_horn_color: 'standard' // Will be udpated by click events to updateCabinet 

}; 

function updateCabinet(component, color) { 
if(!component || !color) return false; // Exit if missing values 

// Take component and update the 'finishes' object above based on which part we are changing 
switch(component) { 
    case 'cabinet': 
     finishes.current_cabinet_color = color; 
     break; 
    case 'horn': 
     if(color != 'piano' && color != 'polar') { 
      finishes.current_horn_color = 'custom'; 
     } else { 
      finishes.current_horn_color = 'standard'; 
     } 
     break; 
    case 'grille': 
     finishes.current_grille_color = color; 
     break; 
    default: 
     return false; // Invalid component name passed in 
} 

// Now that we have updated the 'finishes' object, we can get our xpos and ypos values from it 
xpos = finishes.cabinets[finishes.current_cabinet_color + '_' + finishes.current_horn_color]; 
ypos = finishes.colors[finishes.current_grille_color]; 

// Finally make sure we have good values for xpos and ypos and do the CSS udpate 
if(xpos && ypos) { 
    $('#target').css('background-position', xpos+' '+ypos); 
} 
return true; 
} 

HTML:

<!-- FINISHES --> 
<div id="finishes" class="item"><a name="finishes"></a> 
    <div id="swatches" class="content"> 
     <div class="finishscroll"> 
      <p class="text">Avalon by EAW represents a radical departure from any dance club loudspeaker ever created, including our own original Avalon Series. Everything about Avalon by EAW breaks new ground. The system design turns the loudspeaker inside-out, mounting the MF/HF horn outside the grille. And the grille - concave and sculpted in clean, straight lines - expresses the symmetry that unifies the design.</p> 
      <div id="target"></div> 
      <div id="label-cab" class="label">cabinet</div> 
      <ul id="swatch-cab" class="swatch"> 
       <li class="patch"><a href="#piano" onclick="updateCabinet('cabinet','piano')"><img src="/images/cabinets/swatches/swatch-piano.jpg" /><p>piano</p></a></li> 
       <li class="patch"><a href="#polar" onclick="updateCabinet('cabinet','polar')"><img src="/images/cabinets/swatches/swatch-polar.jpg" /><p>polar</p></a></li> 
      </ul> 
      <div id="label-horn" class="label">horn</div> 
      <div id="content-finishscroll" class="swatch"> 
       <div class="scroll-section"> 
        <ul> 
         <li id="piano" class="patch"> 
          <a href="#" onclick="updateCabinet('horn','piano')"><img src="/images/cabinets/swatches/swatch-piano.jpg" /><p>piano</p></a> 
         </li> 
         <li id="polar" class="patch"> 
          <a href="#" onclick="updateCabinet('horn','polar')"><img src="/images/cabinets/swatches/swatch-polar.jpg" /><p>polar</p></a> 
         </li> 
        </ul> 
       </div> 
      </div> 
     </div> 

     <div class="finishscroll2"> 
      <div id="label-grille" class="label">grille</div> 
      <ul id="swatch-grille" class="swatch"> 
       <li class="patch"><a href="#siren" onclick="updateCabinet('grille','siren')"><img src="/images/cabinets/swatches/swatch-siren.jpg" /><p>siren</p></a></li> 
       <li class="patch"><a href="#medallion" onclick="updateCabinet('grille','medallion')"><img src="/images/cabinets/swatches/swatch-medallion.jpg" /><p>medallion</p></a></li> 
       <li class="patch"><a href="#starlight" onclick="updateCabinet('grille','starlight')"><img src="/images/cabinets/swatches/swatch-starlight.jpg" /><p>starlight</p></a></li> 
       <li class="patch"><a href="#machine" onclick="updateCabinet('grille','machine')"><img src="/images/cabinets/swatches/swatch-machine.jpg" /><p>machine</p></a></li> 
      </ul> 
      <div id="content-finishscroll2"> 
       <div class="swatch" style="width:73px;"> 
        <ul> 
         <li id="siren" class="patch"> 
         <a href="#" onclick="updateCabinet('horn','siren')"><img src="/images/cabinets/swatches/swatch-siren.jpg" /><p>siren</p></a> 
         </li> 
         <li id="medallion" class="patch"> 
         <a href="#" onclick="updateCabinet('horn','medallion')"><img src="/images/cabinets/swatches/swatch-medallion.jpg" /><p>medallion</p></a> 
         </li> 
         <li id="starlight" class="patch"> 
         <a href="#" onclick="updateCabinet('horn','starlight')"><img src="/images/cabinets/swatches/swatch-starlight.jpg" /><p>starlight</p></a> 
         </li> 
         <li id="machine" class="patch"> 
         <a href="#" onclick="updateCabinet('horn','machine')"><img src="/images/cabinets/swatches/swatch-machine.jpg" /><p>machine</p></a> 
         </li> 
        </ul> 
       </div> 
      </div> 
     </div> 
     <div style="position:absolute; top:450px; left:-60px"><img src="http://avalon.eaw.com/images/shadow-finishes.png" /></div> 
    </div> 
</div><!-- #finishes --> 

счастливым кодирования!

Смежные вопросы