2014-11-23 74 views
0

爲交互式圖片我希望圖像改變懸停和保持懸停狀態,如果點擊(見圖片:http://labs.tageswoche.ch/grafik_osze)。對於懸停我有這樣的代碼:改變圖片點擊,保持圖像,並刪除如果其他圖像被點擊

var sourceSwap = function() { 
     var $this = $(this); 
     var newSource = $this.data('alt-src'); 
     $this.data('alt-src', $this.attr('src')); 
     $this.attr('src', newSource); 
    } 

    $(function() { 
     $('img[data-alt-src]').each(function() { 
      new Image().src = $(this).data('alt-src'); 
     }).hover(sourceSwap, sourceSwap); 
    }); 

但我不知道如何adpat此代碼,它的工作還點擊。如果點擊另一張圖像,應再次顯示原始圖像(白色圖像)。所以只有一個點擊圖片是黑色的。謝謝你的回答!

+0

你試過$( 'IMG')。點擊(sourceSwap);? – bondythegreat 2014-11-23 12:14:43

+0

http://jsfiddle.net/abhitalks/mco82kLw/1/ – Abhitalks 2014-11-23 12:15:34

+0

@abhitalks jsfiddle在firefox中不起作用,它在chrome中起作用,但行爲並不完全符合我的要求。當我點擊另一張圖片時,我希望所有其他imgs未點擊/不活動 – Felix 2014-11-23 15:27:52

回答

0
var sourceSwap = function() { 
     var $this = $(this); 
     if (!$this.hasClass('active')) { 
     var newSource = $this.data('alt-src'); 
     $this.data('alt-src', $this.attr('src')); 
     $this.attr('src', newSource); 
     } 
    } 

var makeActive = function() { 
    var $this = $(this); 

    // bring the active back (if any) to the first state 
    if($('img.active').length) { 
     var newSource = $('img.active').data('alt-src'); 
     $('img.active').data('alt-src', $('img.active').attr('src')); 
     $('img.active').attr('src', newSource); 

     $('img.active').removeClass('active'); 
    } 

    $this.toggleClass('active'); 
} 


$(function() { 
    $('img[data-alt-src]').each(function() { 
    new Image().src = $(this).data('alt-src'); 
    }).hover(sourceSwap, sourceSwap); 

    $('img[data-alt-src]').on('click', makeActive); 
}); 

以及我還沒有測試,但我希望你有一點

+0

懸停和點擊工作,但現在如果我點擊在它上面,然後在另一個元素上,兩個元素是黑色的,如何去除這個類?我必須把removeClass放到另一個位置嗎?鏈接已更新 – Felix 2014-11-23 17:47:24

+0

檢查更新的代碼。希望它的作品 – bondythegreat 2014-11-23 19:03:10

+0

perfekt,謝謝! – Felix 2014-11-23 20:41:02