Color Swatch / Variant dropdown list for shopify products

霸气de小男生 提交于 2019-12-03 17:15:58

I used the code from the Shopify article you linked to in your question (Add color swatches to your products) as a starting point and tweaked it to only display one square that changes color depending on the selected option.

Create a new snippet, swatch.liquid (this is a reduced version of swatches.liquid):

<style>

/* Style the swatch */
.swatch { margin:15px 0; }
.swatch ul { list-style-type:none; margin:0; padding:0; }
.swatch li {
  /* Rounded corners */
  -webkit-border-radius:2px;
  -moz-border-radius:2px;
  border-radius:2px;
  /* Cross-browser inline-block */
  display:-moz-inline-stack;
  display:inline-block;
  zoom:1;
  *display:inline;
  /* Content must stretch all the way to borders */
  padding:0;
  /* Background color */
  background-color:#ddd;
  /* Spacing between buttons */
  margin:0px 5px 10px 0;
  /* Fake that those are buttons, i.e. clicky */
  cursor:pointer;
  /* The border when the button is not selected */
  border: #DDD 1px solid !important;
}

/* Styles for the text or color container within the swatch button */
.swatch li span { display:block; margin:5px 10px; }
/* Special styles for color swatches */
/* They don't contain text so they need to have a width and height */
.swatch li.color { width:50px; height:35px; }
/* The container of the image/color must be as big as its container */
.swatch li.color span { width:100%; height:100%; margin:0; }

</style>

<div class="swatch clearfix">
  <ul>
    <li class="color">
      <span></span>
    </li>
  </ul>
</div>

Include the swatch wherever you want it to be displayed in product.liquid:

{% include 'swatch' %}

Add something like this to the selectCallback function:

if (variant) {
  jQuery('.swatch li span').css("background-color", variant.option2); // or whichever option 'colour' is in your case...
}

You'll probably need to adjust that javascript depending on how you have your variants set up. For me, the colour is option2, which is then assigned to the background-color css property of the swatch.

Here's what it looks like in action:

It's a bit rough, but hopefully it will provide you with a starting point.

Edit: gist available here

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!