创建自定义jQuery类

我正在为我的网站创建一个照片库。 我想要一个页面加载时显示的照片网格。 然后,当用户将鼠标hover在每张照片上时,照片会稍微放大。

我为hover创建了javascript,但我不知道如何将其正确打包到类中。

基本上,我想创建一个这样的列表

然后它会使用我的hover机制自动创建每个图像。 到目前为止,这是我的代码。

      .hoverImage { position: absolute; width: 200px; left: 500px; top: 200px; }     var originalWidth; var originalHeight; function onHover() { originalWidth = $(this).width(); originalHeight = $(this).height(); $(this).stop(false, true).animate({ left: $(this).offset().left-(Math.floor(originalWidth/4)), top: $(this).offset().top-(Math.floor(originalHeight/4)), width: 300, },200); } function offHover() { $(this).stop(false, true).animate({ left: $(this).offset().left+(Math.floor(originalWidth/4)), top: $(this).offset().top+(Math.floor(originalHeight/4)), width: 200, },200); } $(document).ready(function() { $("img").hover(onHover, offHover); });     

如果你想用你自己的方法扩展jQuery DOM对象,这应该是这样做的方法

 $.fn.extend({ relyntsHoverPlugin : function() {} }); 

这将允许语法

 $('ul').relyntsHoverPlugin(); 

不要与使用新函数扩展jQuery对象混淆,即。 $ .relyntsMethod();

希望这会有所帮助,而且我并非完全偏离基地!

如果你想将你的function包装成可重用的东西,考虑编写一个jQuery扩展。 这并不难。

这是指南: http : //docs.jquery.com/Plugins/Authoring

您可以使用模板在grid / div / table中创建图像…并为图像添加onHover()和offHover()。 希望它能帮到你。