当我将鼠标悬停在链接上时,此函数会更改链接的类别以更改颜色,但是当我将鼠标悬停在链接上时,它们只会更改一次。我如何在悬停时改变班级?

<script type="text/javascript">
        $(".nav a").hover(function(e){
            var randomClass = getRandomClass();
            $(e.target).attr("class", randomClass);
        });
        $(".text a").hover(function(e){
            var randomClass = getRandomClass();
            $(e.target).attr("class", randomClass);
        });
    function getRandomClass(){
        var classes = new Array("green", "purple", "teal", "violet", "pink", "red", "yellow", "blue", "magenta", "orange");
        var randomNumber = Math.floor(Math.random()*11);
        return classes[randomNumber];
    }
    </script>


谢谢

最佳答案

您可以添加setInterval

像这样:

var textInterval;

$(".text a").hover(function(e) {
  var evt = e;
  textInterval = setInterval(function() {

    var randomClass = getRandomClass();
    $(evt.target).attr("class", randomClass);

  }, 200); //change 200 for the timing you want the interval to repeat in ms
}, function(e) {
  //clear interval when uses moves mouse away
  clearInterval(textInterval);
});

09-25 15:23