【问题标题】:Display random image from file of images in div on page在页面上显示来自 div 中图像文件的随机图像
【发布时间】:2014-09-23 08:49:18
【问题描述】:

如何使用 JQuery 从图像文件中显示随机图像,然后当单击链接时,图像会更改为另一个随机图像。

这是加载图像时需要加载的 img id,如果上面的链接被选中。

    <a href="#imageChange">

    <img id="cap" src="" height="220px" width="530px" />

【问题讨论】:

  • http://stackoverflow.com/questions/17142339/selecting-a-random-image-to-display?rq=1 Mr. Code 在他的回答中做得非常好,我认为这会让你达到 95% 的目标。
  • 生成一个random number并创建一个图像数组,然后使用数组中的数字来选择要加载的图像......然后在点击时生成一个新数字。

标签: javascript jquery html css image


【解决方案1】:

如果您将图像路径保存在数据库中,您可以这样做:

SELECT imagePaths FROM table ORDER BY RAND() LIMIT 1

获取一个随机的图像路径,然后显示它。

使用客户端/服务器端语言,您可以生成一个随机数,作为索引,您将使用该索引从存储所有图像的数组中获取图像路径。

在 javascript 中你可以使用这样的函数:

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

使用 PHP:

$index = rand(0, $nbOfImgs);

【讨论】:

    【解决方案2】:

    一旦您获得图像 URL,此处的 jQuery sn-p 将起作用。 theImageURL 指的是图片的完整 URL。

    $('#imageChange').on('click',function(event){
        event.preventDefault(); // to prevent page from jumping or navigating away
        $('#cap').attr('src',theImageURL); //setting the source for the image.
    });
    

    您也可以调用 $('#cap').load(theImageURL);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-17
      • 2021-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多