点击swatch - Shopify更改产品图片

时间:2018-02-26 05:58:09

标签: javascript jquery shopify liquid

点击色板时,我正在尝试更改shopify页面上的产品图片。但我无法让它发挥作用......

这是我写的代码(如果它是初级的我很抱歉):

<div class="product grid__item {{ grid_item_width }} slide-up-animation 
animated" role="listitem">
  <a href="{{ product.url | within: collection }}" class="product__image" 
    title="{{ product.title | escape }}">
    <img class="theImage" src="{{ product.featured_image.src | img_url: 'grande' 
}}" alt="{{ product.featured_image.alt | escape }}">
  </a>

<div class="product__title text-center">
  <a href="{{ product.url | within: collection }}">{{ product.title }}</a>
</div>

{% if settings.vendor_show %}
<div class="product__vendor text-center">
  {{ product.vendor }}
</div>
{% endif %}    

<!-- COLOR SWATCH -->
<script>
theButton.onclick = function pictureChange()
{
  document.getElementsByClassName("theImage").src="{{% assign featured_image = current_variant.featured_image %}}";
}
</script>
<div class="product__prices text-center">
{% for option in product.options %}
 {% if option == 'Color' %}
  {% assign index = forloop.index0 %}
  {% assign colorlist = '' %}
  {% assign color = '' %}
  {% for variant in product.variants %}
    {% capture color %}{{ variant.options[index] }}{% endcapture %}
    {% unless colorlist contains color %}
      <img class="theButton" src="{{ color | downcase | append: '.gif' | asset_url }}" alt="{{ color }}" width="16" height="16" onclick="pictureChange()" />
      {% capture tempList %}{{colorlist | append: color | append: ‘ ‘}}{% endcapture %}
      {% assign colorlist = tempList %}
    {% endunless %}
  {% endfor %}
{% endif %}
{% endfor %} 
<br/>

有人有指点吗?

当我打开控制台时,它说'theButton未定义'。

谢谢,请帮忙!

1 个答案:

答案 0 :(得分:2)

我也遇到了这个问题并为我的商店排序了这个问题。随着shopify改变了它的结构(分段主题),许多人面临着selectCallback功能的问题。请按照以下步骤在分段主题中添加样本 -

  1. 在代码段中创建swatch.liquid文件。复制下面的代码 -

    {% comment %}
      Set the extension of your color files below. Use 'png', 'jpeg', 'jpg' or 'gif'.
    {% endcomment %}
    
    {% assign file_extension = 'png' %}
    
    {% if swatch == blank %}
    <div class="swatch error">
      <p>You must include the snippet swatch.liquid with the name of a product option.</p> 
      <p>Use: <code>{% raw %}{% include 'swatch' with 'name of your product option here' %}{% endraw %}</code></p>
      <p>Example: <code>{% raw %}{% include 'swatch' with 'Color' %}{% endraw %}</code></p>
    </div>
    {% else %}
    
    {% assign found_option = false %}
    {% assign is_color = false %}
    {% assign option_index = 0 %}
    
    {% for option in product.options %}
      {% if option == swatch %}
        {% assign found_option = true %}
        {% assign option_index = forloop.index0 %}
        <style>
          label[for="product-select-option-{{ option_index }}"] { display: none; }
          #product-select-option-{{ option_index }} { display: none; }
          #product-select-option-{{ option_index }} + .custom-style-select-box { display: none !important; }
        </style>
        <script>jQuery(document).ready(function() { jQuery('.selector-wrapper:eq({{ option_index }})').hide(); });</script>
        {% assign downcased_option = swatch | downcase %}
        {% if downcased_option contains 'color' or downcased_option contains 'colour' %}
          {% assign is_color = true %}
        {% endif %}
      {% endif %}
    {% endfor %}
    
    {% unless found_option %}
    <div class="swatch error">
      <p>You included the snippet swatch.liquid with the name of a product option — <code>'{{ swatch }}'</code> — that does not belong to your product.</p>
      <p>Use <code>{% raw %}{% include 'swatch' with 'name of your product option here' %}{% endraw %}</code></p>
      <p>Example: <code>{% raw %}{% include 'swatch' with 'Color' %}{% endraw %}</code></p>
      <p><strong>This is case-sensitive!</strong> Do not put in <code>'color'</code> if your product option name is <code>'Color'</code>.</p>
    </div>
    {% else %}
    <div class="swatch clearfix" data-option-index="{{ option_index }}">
      <div class="header">{{ swatch }}</div>
      {% assign values = '' %}
      {% for variant in product.variants %}
        {% assign value = variant.options[option_index] %}
        {% unless values contains value %}
          {% assign values = values | join: ',' %}
          {% assign values = values | append: ',' | append: value %} 
          {% assign values = values | split: ',' %}
          <div data-value="{{ value | escape }}" class="swatch-element {% if is_color %}color {% endif %}{{ value | handle }} {% if variant.available %}available{% else %}soldout{% endif %}">
            {% if is_color %}
            <div class="tooltip">{{ value }}</div>
            {% endif %}
            <input id="swatch-{{ option_index }}-{{ value | handle }}" type="radio" name="option-{{ option_index }}" value="{{ value | escape }}"{% if forloop.first %} checked{% endif %} {% unless variant.available %}disabled{% endunless %} />
            {% if is_color %}
            <label for="swatch-{{ option_index }}-{{ value | handle }}" style="background-color: {{ value | split: ' ' | last | handle }}; background-image: url({{ value | handle | append: '.' | append: file_extension | asset_url }})">
              <img class="crossed-out" src="{{ 'soldout.png' | asset_url }}" />
            </label>
            {% else %}
            <label for="swatch-{{ option_index }}-{{ value | handle }}">
              {{ value }}
              <img class="crossed-out" src="{{ 'soldout.png' | asset_url }}" />
            </label>
            {% endif %}
          </div>
        {% endunless %}
        {% if variant.available %}
        <script>
          jQuery('.swatch[data-option-index="{{ option_index }}"] .{{ value | handle }}').removeClass('soldout').addClass('available').find(':radio').removeAttr('disabled');
        </script>
        {% endif %}
      {% endfor %}
    </div>
    
    {% endunless %}
    
    {% endif %}
    
  2. 现在在theme.liquid标记的<script>文件中添加jquery代码,位于底部的关闭</body>标记上方。请参阅以下代码 -

        jQuery(function() {
          jQuery('.swatch :radio').change(function() {
            var optionIndex = jQuery(this).closest('.swatch').attr('data-option-index');
            var optionValue = jQuery(this).val();
            jQuery(this)
            .closest('form')
            .find('.single-option-selector')
            .eq(optionIndex)
            .val(optionValue)
            .trigger('change');
          });
    
          jQuery('.single-option-selector').change(function() {
            var optionValue = jQuery(this).val();
            jQuery(this).closest('form').find('.swatch').each(function( index ) {
              jQuery(this).find(':radio').each(function( index ) {
                if(jQuery(this).val() == optionValue ){
                  $(this).siblings(':radio').prop('checked', false);
                    $(this).prop('checked', true);     
                }   
              });
            });
          });
        });
    
  3. 现在在product-template.liquid正上方的{% schema %}部分添加jquery代码。请参阅以下代码 -

    {% if product.variants.size > 1 %}
        <script>
          var variantImages = {},
            thumbnails,
            variant,
            variantImage,
            optionValue,
            productOptions = [];
            {% for variant in product.variants %}
               variant = {{ variant | json }};
               if ( typeof variant.featured_image !== 'undefined' && variant.featured_image !== null ) {
                 variantImage =  variant.featured_image.src.split('?')[0].replace(/http(s)?:/,'');
                 variantImages[variantImage] = variantImages[variantImage] || {};
                 {% for option in product.options %}
    
                   {% assign option_value = variant.options[forloop.index0] %}
                   {% assign option_key = 'option-' | append: forloop.index0 %}
    
                   if (typeof variantImages[variantImage][{{ option_key | json }}] === 'undefined') {
                     variantImages[variantImage][{{ option_key | json }}] = {{ option_value | json }};
                   }
                   else {
                     var oldValue = variantImages[variantImage][{{ option_key | json }}];
                     if ( oldValue !== null && oldValue !== {{ option_value | json }} )  {
                       variantImages[variantImage][{{ option_key | json }}] = null;
                     }
                   }
                 {% endfor %}
               }
               productOptions.push(variant);
            {% endfor %}
        </script> 
        {% endif %}
    
  4. 现在,在product-template.liquid字段正下方的</select>部分中添加样本 -

    {% if product.available and product.variants.size > 1 %}
                  {% for option in product.options %}
                    {% include 'swatch' with option %}
                  {% endfor %}
                {% endif %}
    
  5. 最后一步是为色板添加css。将css添加到theme.scss.liquid -

    / *     色板样式     * /

    {% assign width = '50px' %}
    {% assign height = '35px' %}
    .swatch { 
      margin:1em 0; 
      width: 100%;
      display: inline-block;
    }
    /* Label */
    .swatch .header {
      margin: 0.5em 0;
    }
    /* Hide radio buttons.*/
    .swatch input { 
      display:none;
    }
    .swatch label {
      /* Rounded corners */
      -webkit-border-radius:2px;
      -moz-border-radius:2px;
      border-radius:2px;
      /* To give width and height */
      float:left;
      /* Color swatches contain no text so they need to have a width. */
      min-width:{{ width }} !important; 
      height:{{ height }} !important;
      /* No extra spacing between them */
      margin:0;
      /* The border when the button is not selected */
      border:#ccc 1px solid;
      /* Background color */
      background-color:#ddd;
      /* Styling text */
      font-size:13px;
      text-align:center;
      line-height:{{ height }};
      white-space:nowrap;
      text-transform:uppercase;
    }
    .swatch-element label { padding:0 10px; }
    .color.swatch-element label { padding:0; }
    /* Styling selected swatch */
    /* Slightly raised */
    .swatch input:checked + label {
      -webkit-box-shadow:0px 1px 2px rgba(0,0,0,0.8);
      -moz-box-shadow:0px 1px 2px rgba(0,0,0,0.8);
      box-shadow:0px 1px 2px rgba(0,0,0,0.8);
      border-color:transparent;
    } 
    .swatch .swatch-element {
      float:left;
      -webkit-transform:translateZ(0); /* webkit flicker fix */
      -webkit-font-smoothing:antialiased; /* webkit text rendering fix */
      /* Spacing between buttons */
      margin:0px 10px 10px 0;
      /* To position the sold out graphic and tooltip */
      position:relative;
    }
    .color.swatch-element label {
      padding: 0;
      min-width: 40px !important;
      height: 40px !important;
      border-radius: 100%;
    }
    /* Image with the cross in it */
    .crossed-out { position:absolute; width:100%; height:100%; left:0; top:0; }
    .swatch .swatch-element .crossed-out { display:none; }
    .swatch .swatch-element.soldout .crossed-out { display:block; }
    .swatch .swatch-element.soldout label {
      filter: alpha(opacity=60); /* internet explorer */
      -khtml-opacity: 0.6;      /* khtml, old safari */
      -moz-opacity: 0.6;       /* mozilla, netscape */
      opacity: 0.6;           /* fx, safari, opera */
    }
    /* Tooltips */
    .swatch .tooltip {
      text-align:center;
      background:gray;
      color:#fff;
      bottom:100%;
      padding: 10px;
      display:block;
      position:absolute;
      width:100px;
      left:{{ width | remove: 'px' | to_number | divided_by: 2 | minus: 50 | plus: 2 }}px;
      margin-bottom:15px;
      /* Make it invisible by default */
      filter:alpha(opacity=0);
      -khtml-opacity: 0;
      -moz-opacity: 0;
      opacity:0;
      visibility:hidden;
      /* Animations */
      -webkit-transform: translateY(10px);
      -moz-transform: translateY(10px);
      -ms-transform: translateY(10px);
      -o-transform: translateY(10px);
      transform: translateY(10px);
      -webkit-transition: all .25s ease-out;
      -moz-transition: all .25s ease-out;
      -ms-transition: all .25s ease-out;
      -o-transition: all .25s ease-out;
      transition: all .25s ease-out;
      -webkit-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
      -moz-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
      -ms-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
      -o-box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
      box-shadow: 2px 2px 6px rgba(0, 0, 0, 0.28);
      z-index: 10000;
      -moz-box-sizing:border-box; 
      -webkit-box-sizing:border-box; 
      box-sizing:border-box;
    }
    .swatch .tooltip:before {
      bottom:-20px;
      content:" ";
      display:block;
      height:20px;
      left:0;
      position:absolute;
      width:100%;
    }
    /* CSS triangle */
    .swatch .tooltip:after {
      border-left:solid transparent 10px;
      border-right:solid transparent 10px;
      border-top:solid gray 10px;
      bottom:-10px;
      content:" ";
      height:0;
      left:50%;
      margin-left:-13px;
      position:absolute;
      width:0;
    }
    .swatch .swatch-element:hover .tooltip {
      filter:alpha(opacity=100);
      -khtml-opacity:1;
      -moz-opacity:1;
      opacity:1;
      visibility:visible;
      -webkit-transform:translateY(0px);
      -moz-transform:translateY(0px);
      -ms-transform:translateY(0px);
      -o-transform:translateY(0px);
      transform:translateY(0px);
    }
    .swatch.error {
      background-color:#E8D2D2!important;
      color:#333!important;
      padding:1em;
      border-radius:5px;
    }
    .swatch.error p {
      margin:0.7em 0;
    }
    .swatch.error p:first-child {
      margin-top:0;
    }
    .swatch.error p:last-child {
      margin-bottom:0;
    }
    .swatch.error code {
      font-family:monospace;
    }
    .product-form__cart-submit {
      width: auto;
      padding-left: 30px;
      padding-right: 30px;
    }
    
    .swatch .color.swatch-element input:checked+label {
      -webkit-box-shadow: 0px 0 5px rgba(0,0,0,1);
      -moz-box-shadow: 0px 0 5px rgba(0,0,0,1);
      box-shadow: 0px 0 5px rgba(0,0,0,1);
    }
    
相关问题