类似亚马逊的界面,用于选择产品尺寸和颜色(即单击红色小框以选择红色产品等)

发布于 2024-07-16 14:19:56 字数 476 浏览 5 评论 0 原文

在我的在线商店中,我想实现一个类似于 亚马逊 的界面来选择产品尺寸和颜色。 即,用户应该看到一堆小框,而不是不同尺寸/颜色的单选按钮,每个小框包含颜色样本或尺寸名称。 当用户单击某个框时,边框应该发生变化以表明它已被选中。

我已经在使用 jQuery,所以我认为 jQuery 可选择小部件 将是一种自然的方式实施这一点。 不幸的是,它似乎无法让您控制用户可以选择的最大项目数,因此我无法限制用户在 UI 中在线选择一种颜色/尺寸。

以 jQuery 友好的方式实现此功能的最佳方式是什么(如果可能)?

In my online store, I want to implement an interface like Amazon's for selecting product size and color. I.e., instead of radio buttons for the different sizes / colors, the user should see a bunch of little boxes, each containing either a swatch of color or the name of a size. When the user clicks a box, the border should change to indicate it's selected.

I'm using jQuery already, so I thought that the jQuery selectable widget would be a natural way to implement this. Unfortunately, it doesn't appear to give you control over the maximum number of items the user can select, and therefore I couldn't limit users to selecting online one color / size in the UI.

What's the best way to implement this functionality in a jQuery-friendly way (if possible)?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

暖风昔人 2024-07-23 14:19:56

以下是如何使用渐进增强正确执行此操作。 这个想法很简单,将一个经过适当标记的 HTML 表单转换为更好的颜色和尺寸样本按钮,供使用 JavaScript 的用户使用。

这种方法的好处很多,您可以轻松切换或删除组件(JS/CSS)并使表单仍然有效。 它将适用于不会使用 javascript 的用户,如果我们小心的话,它将可以通过键盘和屏幕阅读器访问。 它还不需要提交额外的代码,并且与表单验证器一起使用会更容易。

大部分工作都是用 CSS 完成的,只需要很少的 JavaScript 来完成最后的润色。

完整的工作示例可以在 jsbin 上找到。 它包括颜色和尺寸选择。 我在这里只包含了颜色,因为它们之间的 CSS 只有细微的差别。

HTML

首先,标记表单组件。 这是基础知识,您显然可能想要添加一些东西,例如整个小部件的包装器,或使用其他类名。

<label>Color</label>
<ul class="radio color">
  <li class="red">
    <input type="radio" name="color" id="color_red" value="red" />
    <label for="color_red">Red</label>
  </li>
  <li class="green">
    <input type="radio" name="color" id="color_green" value="green" />
    <label for="color_green">Green</label>
  </li>
  <!-- ...and so on... -->
</ul>

对于“基础知识”来说,这似乎很多,但这里发生了几件事。 整个 UL 容器被标记为“radio”,因此其中的所有内容都可以使用 CSS 进行适当的定位(“ul.radio label”)。

此外,我添加了一个与输入名称相对应的类,并在每个 LI 上添加了一个类来回显该值,以允许 CSS 添加适当的样式 ("ul.color li.red" )。 其余的几乎就是您的标准表单标记。

JavaScript

JavaScript 非常简单。 我们所做的就是检测当前选择了哪个无线电输入,并使用“选定”类标记容器 LI,从而允许 CSS 适当地突出显示它。

jQuery(function($){
  // notify CSS that JS is present
  $( 'body' ).addClass( 'js-active' );
  // for every radio control...
  $( 'ul.radio' )
    // redo every change
    .bind('click', function () {
      // refresh "current classes"
      $( 'li', this ).removeClass( 'selected' )
        .filter( ':has(:checked)' ).addClass( 'selected' );
    })
    // trigger initial run
    .trigger( 'click' );  
});

请注意:如果您有更高的点击处理程序(通常为 document.body),这种触发点击以强制初始运行的“技巧”可能不安全,为了简洁起见,我使用此方法。

CSS

这里才是真正神奇的地方。 我们的想法是,我们可以将输入控件隐藏在视图之外,并将标签设置为颜色按钮。 只要标签上的 for 属性正确指向输入上的 id,然后单击标签就足以正确选择控件。

我们只需要定位 ".js-active" 内的内容,以便没有 JavaScript 但仍拥有 CSS 的用户能够看到无线电输入元素。 或者可以在 UL 包装器上添加某种“.radio-js”类来完成相同的操作。

首先,浮动按钮并赋予它们更像按钮的外观:

/* attributes are lined up horizontally */
ul.color li,
ul.size li {
  border : 1px solid #aaa;
  margin : 0 4px 0 0;
  padding : 2px;
  float : left;
  overflow : hidden;
  position : relative;
}

我们在每个 LI 上放置 position:relativeoverflow:hidden ,这样我们就可以将输入元素移出看法。 这将使其保持可访问性,但我们不再需要查看它:

/* if JS: remove inputs from sight */
.js-active ul.color input,
.js-active ul.size input {
  position : absolute;
  left : -999em;
}

下一步是将标签变成按钮:

/* if JS: turn color labels into buttons */
.js-active ul.color label {
  cursor : pointer;
  display : block;
  height : 18px;
  width : 18px;
  text-indent : -999em; /* hide text */
}
/* color buttons in color -- allowed even if no JS */
ul.color li.red label   { background : red;   }
ul.color li.green label { background : green; }
ul.color li.blue label  { background : blue;  }

最后,为突出显示/选定的项目设置一些样式。

/* if JS: current selected highlight */
.js-active ul.color .selected,
.js-active ul.size .selected {
  border : 2px solid #000;
  padding : 1px;
}

为了完整起见: 获取选择value 如果你想添加更多效果,请在其他地方进行演示。

Here is how to do this properly using progressive enchancement. The idea is simple, turn a decently marked up HTML form into nicer color and size swatch buttons for users that have JavaScript.

The benefits of this method are many, you can easily switch, or remove, components (JS/CSS) and have the form still work. It will work for users that don't hvae javascript, and if we're careful, it will be accessible via keyboard and screen readers. It also requires no extra code on submit, and will be a lot easier to use with a form validator.

Most of the work is done with CSS with only minimal JavaScript to add the finishing touches.

Full working example example can be found on jsbin. It includes both color and size selections. I have only included the colors here as there is only a slight difference in the CSS between the them.

The HTML

First off, markup the form components. Here are the basics, you may obviously want to add things, like a wrapper around the whole widget, or use other classnames.

<label>Color</label>
<ul class="radio color">
  <li class="red">
    <input type="radio" name="color" id="color_red" value="red" />
    <label for="color_red">Red</label>
  </li>
  <li class="green">
    <input type="radio" name="color" id="color_green" value="green" />
    <label for="color_green">Green</label>
  </li>
  <!-- ...and so on... -->
</ul>

This may seem a lot for "basics", but there are several things going on here. The whole UL container is flagged as "radio" so everything within can be targeted appropriately with CSS ("ul.radio label").

Additionally I add a class corresponding to the input's name, and a class on each LI echoing the value to allow CSS to add appropriate styles ("ul.color li.red"). The rest is pretty much your standard form markup.

The JavaScript

The JavaScript is very simple. All we do is detect which radio input is currently selected and flag the container LI with a "selected" class, thus allowing CSS to highlight it appropriately.

jQuery(function($){
  // notify CSS that JS is present
  $( 'body' ).addClass( 'js-active' );
  // for every radio control...
  $( 'ul.radio' )
    // redo every change
    .bind('click', function () {
      // refresh "current classes"
      $( 'li', this ).removeClass( 'selected' )
        .filter( ':has(:checked)' ).addClass( 'selected' );
    })
    // trigger initial run
    .trigger( 'click' );  
});

Please note: This "trick" of triggering click to enforce the initial run may be unsafe if you have click handlers higher (typically document.body), I use this method for brevity.

The CSS

Here is where the real magic happens. The idea is that we can tuck the input controls out of view and style the labels as color buttons. So long as the for attributes on the labels correctly point to id's on the inputs then clicking the labels will suffice to select the control correctly.

We need to target things only within ".js-active" so that users that don't have JavaScript but still have CSS will see the radio input elements. Some sort of ".radio-js" class could alternatively be added on the UL wrapper to get the same thing done.

Firstly, float the buttons and give them a more button-like appearance:

/* attributes are lined up horizontally */
ul.color li,
ul.size li {
  border : 1px solid #aaa;
  margin : 0 4px 0 0;
  padding : 2px;
  float : left;
  overflow : hidden;
  position : relative;
}

We put position:relative and overflow:hidden on each LI so we can shift the input element out of view. This will keep it accessible, but we just no longer have to look at it:

/* if JS: remove inputs from sight */
.js-active ul.color input,
.js-active ul.size input {
  position : absolute;
  left : -999em;
}

Next up is turning the labels into buttons:

/* if JS: turn color labels into buttons */
.js-active ul.color label {
  cursor : pointer;
  display : block;
  height : 18px;
  width : 18px;
  text-indent : -999em; /* hide text */
}
/* color buttons in color -- allowed even if no JS */
ul.color li.red label   { background : red;   }
ul.color li.green label { background : green; }
ul.color li.blue label  { background : blue;  }

Finally, set some styles for our highlighted / selected item.

/* if JS: current selected highlight */
.js-active ul.color .selected,
.js-active ul.size .selected {
  border : 2px solid #000;
  padding : 1px;
}

For completeness: Getting the select values if you want to add more effects is demonstrated elsewhere on SO.

谁的年少不轻狂 2024-07-23 14:19:56

可以让 jQuery selectable 阻止选择,尽管不幸的是它不是很直观:

$('#selectable').selectable({
   selected: function(event, ui) {
       var total = $(ui.selected).siblings('li.ui-selected').length + 1;
       if(total > 1) {
           $(ui.selected).removeClass('ui-selected');
       }
   }
});

这将阻止在可选小部件上进行超过 1 个选择的任何操作。

剩下的只是根据您的特定需求进行定制。

编辑:我有点无聊,所以我实现了更多,这样你就可以得到一个想法。

查看工作演示。 对于尺寸和颜色所做的事情有很多重复,您可能可以摆脱它们,但我想将它们分开,因为我认为两者之间的事情可能会发生变化。 不管怎样,这应该会给你一个很好的开始。

It is possible to have jQuery selectable prevent selection, although unfortunately it is not very intuitive:

$('#selectable').selectable({
   selected: function(event, ui) {
       var total = $(ui.selected).siblings('li.ui-selected').length + 1;
       if(total > 1) {
           $(ui.selected).removeClass('ui-selected');
       }
   }
});

That will stop anything past 1 selection being made on a selectable widget.

The rest is just customizing it for your specific needs.

EDIT: I got a little bit bored so I implemented some more so you could get an idea.

Check out a working demo. There is a lot of repetition for things done to sizes and colors that you can probably get rid of but I wanted to keep them separate because I'd imagine things could change between the two. Anyways, that should give you a pretty good start.

你如我软肋 2024-07-23 14:19:56

如果您的目标是只允许选择一个项目,则可以这样做:

$(function() {
    $("#selectable").selectable({
        // this will prevent selecting a second item (for dragging\clicking)
        selecting: function(event,ui) {
            if ($(ui.selecting).siblings("li.ui-selecting").length > 0)
                $(ui.selecting).removeClass("ui-selecting");
        },
        // this will prevent selecting a second item (for CTRL+Click)
        selected: function(event,ui) {
            if ($(ui.selected).siblings("li.ui-selected").length > 0)
                $(ui.selected).removeClass("ui-selected");
        },
        // this will prevent un-selecting items (one item must be selected)
        unselected: function(event,ui) {
            if ($(ui.unselected).siblings("li.ui-selecting").length == 0)
                $(ui.unselected).addClass("ui-selected");
        }
    })
});

此代码将允许选择单个项目,并且无论是通过鼠标拖动还是使用 CTRL+单击,都将阻止选择另一个项目。 它还将防止取消选择项目。 它的行为与亚马逊非常相似。

选择某个项目后,您可以使用 stop 事件在页面上执行更改(类似于 JQuery UI 附带的示例)。

If your goal is to allow only one item to be selected, this will do it:

$(function() {
    $("#selectable").selectable({
        // this will prevent selecting a second item (for dragging\clicking)
        selecting: function(event,ui) {
            if ($(ui.selecting).siblings("li.ui-selecting").length > 0)
                $(ui.selecting).removeClass("ui-selecting");
        },
        // this will prevent selecting a second item (for CTRL+Click)
        selected: function(event,ui) {
            if ($(ui.selected).siblings("li.ui-selected").length > 0)
                $(ui.selected).removeClass("ui-selected");
        },
        // this will prevent un-selecting items (one item must be selected)
        unselected: function(event,ui) {
            if ($(ui.unselected).siblings("li.ui-selecting").length == 0)
                $(ui.unselected).addClass("ui-selected");
        }
    })
});

This code will allow a single item to be selected, and it will prevent selecting another item whether by mouse-dragging or using CTRL+click. It will also prevent un-selecting items. It has very similar behavior to what Amazon have.

You can use the stop event to perform changes on the page after an item is selected (similar to the examples that comes with JQuery UI).

就此别过 2024-07-23 14:19:56

伙计,亚马逊的界面很难看。 我很想尝试更多类似的东西:

尺寸应该足够简单。 不过,我可能会拍摄不同尺寸衬衫的小照片,有点像这里:

(这是我能找到的选择衬衫尺码的最好例子,大多数地方都非常糟糕)

Man, that Amazon interface is ugly. I'd be tempted to try something more along the lines of:

  • Simple Color Picker (naturally, you would not use the hex representation of the color in the picker)
  • Color Picker (although this is probably a little more control than they would need over the color)
  • Flat Color Picker (almost as ugly as the Amazon one)

Sizes should be easy enough. I'd probably do little pictures of shirts of different sizes though, sort of like here:

(that's the best example of picking shirt size that I could find, most places are pretty awful)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文