提问者:小点点

如何使用jquery和scale(css)放大/缩小每个div中的每个图像?


我试图在网站www.nhadatsonnghia.com的一篇文章中为图像创建一个放大/缩小功能。当一切正常工作时,出现了一个错误,即jquery只对第一个标记中的第一个图像起作用,并且后续每个标记中的图像无法放大/缩小。运行后,只有第一个图像具有style=“transform:scale(1);”类。

你可以看到它在这里工作

那么我应该如何修正放大/缩小每个div中的每个图像呢?如果你能建议我如何解决这个问题,我将不胜感激!

谢谢!

这是密码

jQuery

$(function() {
    $('.post-header .desc-image-list .full .natural-thumbnail #img').data('scale', '1');
    $('#nav input').on('click', function() {
        var scale  = parseInt($('#img').data('scale')*10,10),
            nScale = $(this).index()===0 ? scale+1 : scale-1;
            nScale = parseFloat(parseInt(nScale,10)/10);
        $('#img').data('scale', nScale).css('transform', 'scale('+nScale+')');
    });
});

HTML

<div class="post-header">
    <div class="desc-image-list">
        <div class="full">
            <div class="natural-thumbnail">
                <img id="img" src="image1.img">  // After running only the first image has class style="transform: scale (1);"
                <div id="nav">
                    <input type="button" value="Zoom in">
                    <input type="button" value="Zoom out">
                </div>
            </div>
            <div class="natural-thumbnail" style="height: 600px;">
                <img id="img" src="image2.img">
                <div id="nav">
                    <input type="button" value="Zoom in">
                    <input type="button" value="Zoom out">
                </div>
            </div>
            <div class="natural-thumbnail" style="height: 0;">
                <img id="img" src="image3.img">
                <div id="nav">
                    <input type="button" value="Zoom in">
                    <input type="button" value="Zoom out">
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#nav {position: sticky; bottom: 20px; left: 50%; margin-left: -50px;}
#nav input {padding: 5px; font-size: 15px; cursor: pointer;}


共1个答案

匿名用户

除了@freedomn-m答案。

您可以使用img标记作为css选择器。Natural-Thumbnail img您不需要任何类。更新下面的js和将工作良好。

$(function() {
    $('.post-header .desc-image-list .full .natural-thumbnail img').data('scale', '1');
    $('#nav input').on('click', function() {
        var scale  = parseInt($('.natural-thumbnail img').data('scale')*10,10),
            nScale = $(this).index()===0 ? scale+1 : scale-1;
            nScale = parseFloat(parseInt(nScale,10)/10);
        $('#img').data('scale', nScale).css('transform', 'scale('+nScale+')');
    });
});