模仿淘宝商品选择颜色和尺寸的效果,即选择商品颜色和尺寸的时候,把选择的颜色和尺寸放到一个页面容器里面,不足之处,还望指教。
<!DOCTYPE HTML> <html lang="en-US"> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> .ibWrapper{font-size:0;letter-spacing:-1px;} .ib{font: 12px/18px arial;display:inline-block;} .selectedcolor span{display:block;width:10px;height:10px;} </style> <script type="text/javascript" src="jquery_v1.7.2.js"></script> <script type="text/javascript"> $(document).ready(function (){//注意修改jquery的路径 var sRGBToHex = function (str){ if (str.search(/rgb/i) === -1){//兼容ie6-8,它们的颜色值本身就是16进制的 return str; } var result = "#"; str = str.replace(/rgba?((.*))/gi,"$1"); aStr = str.split(","); for (var i=0; i<3; i++){//这里直接写了3,是因为标准浏览器的色彩值可能包含透明度信息,例如RGBA(0,255,30,0.5) var iColorAlpha = +aStr[i]; if (iColorAlpha < 16){ result += "0" + iColorAlpha.toString(16); }else{ result += iColorAlpha.toString(16); } } return result; } $("#colorList input").click(function (){ var _this = $(this); if ($(this).is(":checked")){ var oSelectedElement = $("<div class='selectedcolor ib' ></div>"); oSelectedElement.text($(this).parent().text()); $("<span>").appendTo(oSelectedElement).end().css("backgroundColor",function (){ return _this.attr("value"); }); oSelectedElement.appendTo($("#selectedColorList")); }else{ $(".selectedcolor span").each(function (i){ if (sRGBToHex($(this).css("backgroundColor")) === _this.attr("value")){ $(this).parent().remove(); } }) } }) }) </script> </head> <body> <div id="colorList"> <form action="#" method="post"> <label ><input type="checkbox" name="temp_color" id="color1" value="#ff0000"/>红色</label> <label ><input type="checkbox" name="temp_color" id="color2" value="#ffff00"/>黄色</label> <label ><input type="checkbox" name="temp_color" id="color3" value="#00ff00"/>绿色</label> <label ><input type="checkbox" name="temp_color" id="color4" value="#0000ff"/>蓝色</label> </form> </div> <div id="selectedColorList" class="ibWrapper"> </div> </body> </html>