简体   繁体   English

使用jQuery旋转图像阵列中的单个图像

[英]Rotate single image in array of images using jQuery

I have an array of images. 我有一系列图像。 Each iteration displays an image and a button. 每次迭代都会显示一个图像和一个按钮。 I want to rotate the image 90 degrees by clicking the button. 我想通过单击按钮将图像旋转90度。 I prefer to do it using jQuery. 我更喜欢使用jQuery。

Loop code (PHP with Twig): 循环代码(PHP和Twig):

{% for key, file in image_files %}
    <div class="image-box">
        <img class="patient-image" data-uniqueid="{{ key }}" src="/{{ src_path }}{{ file }}">
        <p>
            <a class="rotate-btn btn" data-imageid="{{ key }}">Rotate</a>
        </p>
    </div>
{% endfor %}

The data attribute is used to store the element's index value by passing the key value to data-imageid in the button in order to link it to the image which assigns the same key value to data-uniqueid . data属性用于通过将键值传递给按钮中的data-imageid来存储元素的索引值,以便将其链接到将相同键值分配给data-uniqueid On inspection, the values match for each button and image. 经过检查,每个按钮和图像的值均匹配。

Here's the jQuery to retrieve data- values: 这是用于检索data-值的jQuery:

$( '.rotate-btn' ).on('click', function() {

    // get value of data-imageid from button
    var id = $( this ).data().imageid;

    // get value of data-uniqueid from image
    var imageid = $('.patient-image').data().uniqueid;

});

When I click the rotate button on the first image, the values of id and imageid match. 当我单击第一张图像上的“旋转”按钮时, idimageid的值匹配。 But on the second image the value of id is correct but the value of imageid is incorrect. 但是在第二张图像上, id的值正确,但是imageid的值不正确。 It matches the first image value and not the image clicked. 它匹配第一个图像值,而不是单击的图像。

Any help identifying where my error(s) might be is appreciated. 可以帮助您识别我的错误所在的任何帮助。 I am uncertain whether I am approaching this correctly. 我不确定我是否正确处理此问题。

The following is not tested but will, I hope, help. 以下内容未经测试,但希望会有所帮助。 There should be no need to use IDs to target elements as you are trying to do - simply use sibling and parent selectors in conjunction with querySelector / querySelectorAll . 在尝试操作时,无需使用ID来定位元素-只需将同级和父选择器与querySelector / querySelectorAll结合使用即可。 I believe jQuery has it's own methods for this but I cannot advise as to what they are. 我相信jQuery有它自己的方法,但是我不能建议它们是什么。

The idea here is that you obtain a reference to all the buttons used to rotate the images and assign a generic event handler to each. 这里的想法是获得对用于旋转图像的所有按钮的引用,并为每个按钮分配一个通用事件处理程序。 The event handler when invoked clears any previously assigned rotated classes and assigns this css class to the button's sibling image. 调用时,事件处理程序将清除所有先前分配的rotated类,并将此css类分配给按钮的同级图像。

{% for key, file in image_files %}
    <div class='image-box'>
        <img class='patient-image' src='/{{ src_path }}{{ file }}'>
        <p>
            <a class='rotate-btn btn'>Rotate</a>
        </p>
    </div>
{% endfor %}

a tested version 经过测试的版本

    for( $i=0; $i < 10; $i++ ){
        echo "
<div class='image-box'>
    <img class='patient-image' src='/images/homer_2.png'>
    <p>
        <a href='#' class='rotate-btn btn'>Rotate</a>
    </p>
</div>";
    }

测试中使用的源图像

    <style>
        .image-box{clear:none; display:inline-block; margin:1rem; float:left;}
        .rotate-btn{padding:1rem;border:1px solid black;background:whitesmoke;cursor:pointer}
        img{ transform:rotate(0deg); transition: all 250ms ease-in-out;  }
        .rotated{ transform:rotate(90deg) }
    </style>


    <script>
        Array.prototype.slice.call( document.querySelectorAll( 'a.rotate-btn' ) ).forEach( bttn=>{

            bttn.addEventListener('click', function(e){
                e.preventDefault();

                /* if other \"rotated\" images are to revert to their original orientation, else remove this or comment it out */
                Array.prototype.slice.call( document.querySelectorAll('img.rotated') ).forEach( img=>{img.classList.remove('rotated') }) 

                /* apply the css class to perform the rotation */
                let img=this.parentNode.parentNode.querySelector('img');
                    img.classList.add( 'rotated' );
            });
        });
    </script>

结果显示 The result: 结果:

var imageid = $('.patient-image').data().uniqueid;

应该

var imageid = $(this).parent().siblings('.patient-image').data().uniqueid;

The problem is that using the jQuery function $('.patient-image') without context , you will retrieve all elements having the class patient-image . 问题是,使用不带上下文的jQuery函数$('.patient-image') ,您将检索所有具有class patient-image元素。 When you apply .data() to the selection of elements, it will be used on the first one . 当您将.data()应用于元素选择时,它将在第一个元素上使用。 That's why the value is only right the first time. 这就是为什么该值第一次才是正确的。

I think what you want is the element closest to the button clicked. 我认为您想要的是最接近所单击按钮的元素。

var imageid = $(this).closest('.patient-image').data().uniqueid;

is therefore my suggestion. 因此是我的建议。 In case you are only using the "id" and "uniqueid" for identifying the corresponding element, it should become obsolete using this approach. 如果仅使用“ id”和“ uniqueid”来标识相应的元素,则使用此方法应使其过时。

I'd also suggest using $(...).data('uniqueid') instead of getting all the data everytime. 我也建议使用$(...).data('uniqueid')而不是每次都获取所有数据。

To rotate the corresponding image, use the following snippet: 要旋转相应的图像,请使用以下代码段:

$( '.rotate-btn' ).on('click', function() {
  $(this)
    .closest('.patient-image')
    .css('transform', 'rotate(90deg)')
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM