每次将元素悬停时如何显示随机图像?

时间:2019-06-19 05:42:11

标签: jquery

我试图在每个悬停上显示不同的随机图像。当鼠标指针移开并移回该元素时,我想显示一个新图像。我设法允许图像显示在鼠标悬停上,但是我无法使图像在每个新的悬停上都不同(无需刷新)。

图像源是使用PHP生成的,并且经过了改组,所以我认为我不需要多个源。

jsfiddle在这里: https://jsfiddle.net/6cn9xgz8/

任何建议将不胜感激!

  <a class="onhover-toggle-child-class" data-target=".target" data-toggle="hidden shown">Link
   <span class="target hidden">
    <div><img src="https://via.placeholder.com/150"></div>
   </span>
  </a>
.hidden {
  display: none;
}

.shown {
  display:block;
}
  $('.onhover-toggle-child-class').on(
    'mouseenter mouseleave',
    function() {
      var element = $(this);
      var selector = element.data('target');
      var child = element.find(selector);
      var classes = element.data('toggle');


      child.toggleClass(classes);
    }
  );

2 个答案:

答案 0 :(得分:0)

解决方案是您应创建图像链接的array,并使用Math.floor(Math.random() * 5);从长度中获取随机索引

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width='device-width', initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <style>
        .hidden {
            display: none;
        }

        .shown {
            display: block;
        }
    </style>
</head>

<body>
    <a class="onhover-toggle-child-class" data-target=".target" data-toggle="hidden shown">Link
        <span class="target hidden">
            <div><img src="https://via.placeholder.com/150"></div>
        </span>
    </a>
    <script src="https://code.jquery.com/jquery-3.4.1.js"
        integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
    <script>
        var cars = ["https://via.placeholder.com/150", "https://via.placeholder.com/250", "https://via.placeholder.com/350","https://via.placeholder.com/450","https://via.placeholder.com/550"];

        $('.onhover-toggle-child-class').on(
            'mouseenter mouseleave',
            function () {
                var random = Math.floor(Math.random() * 5); // returns a random integer from 0 to 4
                var imageUrl = cars[random];
                $('img').attr("src", imageUrl);
                var element = $(this);
                var selector = element.data('target');
                var child = element.find(selector);
                var classes = element.data('toggle');


                child.toggleClass(classes);
            }
        );
    </script>
</body>

</html>

希望这有帮助 谢谢

答案 1 :(得分:0)

<script>
    var imagesArray = ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg"];

    $(document).on("mouseenter", "#myImg", function(){
        var num = Math.floor(Math.random() * (imagesArray.length));
        var imgSrc= "'"+imagesArray[num]+"'";
        $(".randomImg").attr("src", imgSrc);
    });

</script>

<button id="myImg" type="button">Hover me</button>
<br><br>
<img src="default.jpg" class="randomImg" />