Jquery选择图像

主要是,我是Jquery的新手。

我有这样的图像。 我想要的是,当用户点击图像时,它会使图像边界化。 用户可以选择多个图像。 选中后,所有这些都必须接壤。 单击按钮后,我将有图像ID。

<img id="i will put value for db processing"src="http://sofzh.miximages.com/jquery/urlofimage"   

在此处输入图像描述

我怎样才能做到这一点?

你的意思是:

 $.fn.hasBorder = function() { if ((this.outerWidth() - this.innerWidth() > 0) || (this.outerHeight() - this.innerHeight() > 0)){ return true; } else{ return false; } }; $(document).ready(function() { var selectedImgsArr = []; $("img").click(function() { if($(this).hasBorder()) { $(this).css("border", ""); //you can remove the id from array if you need to } else { $(this).css("border", "1 px solid red"); selectedImgsArr.push($(this).attr("id")); //something like this } }); }); 

一个简单的例子:

在JsBin的现场例子

造型:

 ul { list-style: none; } ul li { display: inline; } ul li img { border: 2px solid white; cursor: pointer; } ul li img:hover, ul li img.hover { border: 2px solid black; } 

javascript:

 $(function() { $("img").click(function() { $(this).toggleClass("hover"); }); $("#btn").click(function() { var imgs = $("img.hover").length; alert('there are ' + imgs + ' images selected'); }); }); 

结果:

在此处输入图像描述

很简单,只需在点击时为图像添加一个新的CSS类。

  ...  ...    

为了简单地从function中删除样式元素,我更喜欢使用此方法来编写样式定义。 使所有内容都可重用,如果需要,以后可以轻松更改。 上面的代码支持应用格式化并在次要点击时删除它。 (IE:如果它存在,它将删除。)

给他们所有的课程:

   

首先为选择添加一个类,然后在发布表单时将项添加到具有“selected-image”类的数组中

 $(document).ready(function() { var selectedImgsArr = new Array(); $("img").click(function() { if($(this).hasClass("selected-image")) $(this).removeClass("selected-image"); else $(this).addClass("selected-image"); }); $("form").submit(function(){ selectedImgsArr.push($(".selected-image").attr("src")); }) });