简体   繁体   English

jQuery - 切换多个图像并保持 div 高度

[英]jQuery - Toggle Multiple Images & Maintain div Height

I am currently using an on click function to toggle between 2 images and it is working like a charm but I was wondering how I would add more images to the sequence?我目前正在使用点击功能在 2 张图像之间切换,它的工作原理很吸引人,但我想知道如何向序列中添加更多图像? The second part of my question is, is it possible to maintain the height of the div when toggling between the images as it currently collapses the height to (display: none) during the transition.我的问题的第二部分是,是否可以在图像之间切换时保持 div 的高度,因为它在过渡期间当前将高度折叠到(显示:无)。

$('#image').on('click', function() {
  let src = ($(this).attr('src') === 'image/1.jpg')
    ? 'image/1.jpg'
    : 'image/2.jpg';

  $(this)
    .fadeOut(500, () => $(this).attr('src', src))
    .fadeIn(500);
});

Thank you all for your help!谢谢大家的帮助!

JSFiddle - https://jsfiddle.net/camusahn/u4rspwya/ JSFiddle - https://jsfiddle.net/camusahn/u4rspwya/

you can store your images in an array then pick randomly on click.您可以将图像存储在一个数组中,然后在单击时随机选择。 Just take a look on what I have done though in my codepen:看看我在我的代码笔中做了什么:

https://codepen.io/jcarizon/pen/MWWLyOP https://codepen.io/jcarizon/pen/MWWLyOP

$('#image').on('click', function() {
  const images = [
    "https://dummyimage.com/100x100/fff000/ffffff",
    "https://dummyimage.com/100x100/ff0000/ffffff",
    "https://dummyimage.com/100x100/0f0f11/ffffff"
  ];
  const randomImages = images[Math.floor(Math.random() * images.length)];

  let src = randomImages;

  $(this)
    .fadeOut(500, () => $(this).attr('src', src))
    .fadeIn(500);
});
<img id="image" src="https://dummyimage.com/100x100/000000/ffffff" alt="dummy" />

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

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