创建自定义jQuery类 [英] Creating custom jQuery class
问题描述
我正在为我的网站创建一个照相馆.我想要页面加载时显示的照片网格.然后,当用户将鼠标悬停在每张照片上时,照片会放大一点.
I am creating a photo gallery for my website. I want a grid of the photos displayed when the page loads. Then when the user hovers over each photo, the photo enlarges a little.
我创建了用于悬停的javascript,但是我不知道如何将其正确打包到一个类中.
I created the javascript for the hovering, but I do not know how to properly package this into a class.
基本上,我只想创建一个这样的列表
Basically, I want to just create a list like this
<ul>
<li><img src="img1.jpg" /></li>
<li><img src="img2.jpg" /></li>
</ul>
然后它会自动使用我的悬停机制来创建每个图像. 到目前为止,这是我的代码.
And then it automatically creates each image with my hovering mechanism already in place. Here is my code thus far.
<!DOCTYPE HTML>
<html>
<head>
<script src="jquery.js"></script>
<style text="text/css">
.hoverImage {
position: absolute;
width: 200px;
left: 500px;
top: 200px;
}
</style>
</head>
<body>
<script>
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);
});
</script>
<img class="hoverImage" src="Test.jpg"/>
</body>
</html>
推荐答案
如果要使用自己的方法扩展jQuery DOM对象,这应该是这样做的方法
If you want to extend the jQuery DOM object with your own method this should be the way to do it
$.fn.extend({
relyntsHoverPlugin : function() {}
});
这将允许使用类似的语法
this will allow for syntax like
$('ul').relyntsHoverPlugin();
不要与使用新功能扩展jQuery对象(即)混淆. $ .relyntsMethod();
Not to be confused with extending the jQuery object with a new function, ie. $.relyntsMethod();
希望这会有所帮助,而且我并没有完全脱离基地!
Hope this helps and that I wasn't totally off base!
这篇关于创建自定义jQuery类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!