簡體   English   中英

如何使用 jquery 和縮放(css)放大/縮小每個 div 中的每個圖像?

[英]How to zoom in/zoom out each image in each div with jquery and scale (css)?

我正在嘗試為網站 www.nhadatsonnghia.com 的文章中的圖像創建放大/縮小 function。 當一切正常時,出現錯誤,jquery 僅適用於第一個標簽中的第一個圖像,並且每個后續標簽中的圖像無法放大/縮小。 運行后只有第一個圖像有 class 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;}

除了@freedomn-m 答案。

您可以將img標簽用作 css 選擇器.natural-thumbnail img您不需要任何 class。 在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+')');
    });
});

元素 ID 在一個 html 頁面上應該是唯一的。

你可以用這個

$(this).parent().siblings('img').data('scale', nScale).css('transform', 'scale('+nScale+')');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM