2

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

我为悬停创建了 javascript,但我不知道如何正确地将其打包到一个类中。

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

<ul>
 <li><img src="img1.jpg" /></li>
 <li><img src="img2.jpg" /></li>
</ul>

然后它会自动创建每个图像,我的悬停机制已经到位。到目前为止,这是我的代码。

<!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>
4

3 回答 3

1

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

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

于 2012-05-15T05:47:39.127 回答
1

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

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

这将允许像这样的语法

$('ul').relyntsHoverPlugin();

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

希望这会有所帮助,并且我并没有完全脱离基地!

于 2012-05-15T05:47:42.550 回答
0

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

 <script type="text/javascript">
    $(document).ready(function() {
    var data = [
    { name: "Astor", product: "astor", stocklevel: "10"},
    { name: "Daffodil", product: "daffodil", stocklevel: "12"},
    { name: "Rose", product: "rose", stocklevel: "2"},
    { name: "Peony", product: "peony", stocklevel: "0"},
    ];
    $('#flowerTmpl').tmpl(data).appendTo('#row1');
    });
    </script>

    <script id="flowerTmpl" type="text/x-jquery-tmpl">
    <div class="dcell">
    <img src="${product}.png"/>
    <label for="${product}">${name}:</label>
    </div>
    </script>
于 2012-05-15T05:55:52.887 回答