2012-11-06 43 views
0

我需要將圖像拆分爲用戶可以懸停或點擊的方形瓷磚。jquery插件創建具有背景圖像的方形瓷磚

我應該使用純CSS還是必須使用jQuery?你有這樣做的jQuery插件的例子嗎? (我發現this one,但會對其他建議感興趣)

感謝您的幫助。

+0

什麼是「我期待更多的」是什麼意思? –

回答

2

把插件是有點老了,我建議你使用這一個,改編自this other plugin

演示:http://jsfiddle.net/elclanrs/HmpGx/

;(function($, window) { 

    var _defaults = { x: 3, y: 3, gap: 2 }; 

    $.fn.splitInTiles = function(options) { 

    var o = $.extend({}, _defaults, options); 

    return this.each(function() { 

     var $container = $(this), 
      width = $container.width(), 
      height = $container.height(), 
      $img = $container.find('img'), 
      n_tiles = o.x * o.y, 
      wraps = [], $wraps; 

     for (var i = 0; i < n_tiles; i++) { 
     wraps.push('<div class="tile"/>'); 
     } 

     $wraps = $(wraps.join('')); 
     $img.hide().after($wraps); 

     $wraps.css({ 
     width: (width/o.x) - o.gap, 
     height: (height/o.y) - o.gap, 
     marginBottom: o.gap +'px', 
     marginRight: o.gap +'px', 
     backgroundImage: 'url('+ $img.attr('src') +')' 
     }); 

     $wraps.each(function() { 
     var pos = $(this).position(); 
     $(this).css('backgroundPosition', -pos.left +'px '+ -pos.top +'px'); 
     }); 

    }); 

    }; 

}(jQuery, window)); 
+0

非常感謝!非常有用 – Mathieu

+0

'0,0'有什麼意義?你可以使用'1,1'或'.hide()'... – elclanrs

+0

嘿,謝謝你的回答。我創建了一個新的相關問題,如果你願意: - )http://stackoverflow.com/questions/23567020/optimize-rendering-speed-of-tile-grid-with-background-image-html5-dom-帆布 – Mathieu