2012-04-16 107 views
2

主要是,我是新的Jquery。Jquery選擇圖像

我有這樣的圖像。我想要的是,當用戶點擊圖像時,它會使圖像接壤。用戶可以選擇多個圖像。這一切都必須選擇邊界。點擊按鈕後,我將有圖像ID。

<tr><img id="i will put value for db processing"src="urlofimage"</tr> &nbsp; 

enter image description here

我怎樣才能做到這一點?

回答

5

你的意思是:


$.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 
     } 
    }); 
}); 
+0

是的,這將使圖像接壤,我想要的是選定的圖像將作爲數組發送。我怎樣才能做到這一點? – 2012-04-16 07:43:21

+0

只是一個建議,如果再次點擊圖片時邊框會變得不錯 – 2012-04-16 07:46:57

+0

看到編輯好的代碼,應該可以工作,但是使用class對你來說是更好的解決方案 – 2012-04-16 07:55:31

1

給他們所有的類:

<tr><img class="clickable" id="i will put value for db processing" src="urlofimage" /></tr> 

<script> 
    $(document).ready(function() { 
     var clickedarray = new Array(); 
     $('.clickable').click(function() { 
      //add border 
      $(this).css({border: '1px solid #000'}); 
      //store in array 
      clickedarray.push($(this).attr('id')); 
     }); 
    }); 
</script> 
2

一個簡單的例子:

live example in 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');   
    }); 

}); 

結果:

enter image description here

1

第一添加一個類用於選擇,然後將項目添加到陣列有「選擇圖像」級而形式發佈

$(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")); 
    }) 
}); 
+0

您是否介意在英文中翻譯那麼一點點的文字我們的質量檢驗員不會發瘋? – rene 2014-11-19 20:54:57

2

很簡單,只需在點擊圖片上添加一個新的CSS類。

<html> 
... 
<td><img class='galImages' src='urlofimage' /></td> 
... 
</html> 

<script> 
$document.ready(function() { 
    $('img.galImages').click(function() { 
     if($(this).hasClass('selected')) { 
      $(this).removeClass('selected'); 
     } 
     else { 
      $(this).addClass('selected'); 
     } 
    }); 
}); 
</script> 

<style> 
.selected { 
    1px solid #f00; 
} 
</style> 

爲了簡單地從功能中刪除文體元素,我更喜歡使用此方法對腳本樣式定義。使所有事情都可以重複使用,並且如果需要的話可以稍後更改。以上代碼支持應用格式並在輔助點擊中刪除它。 (IE:它會刪除,如果它存在。)