【问题标题】:How can i make this function infinite while hovering悬停时如何使此功能无限
【发布时间】:2015-07-15 10:58:12
【问题描述】:

当我将鼠标悬停在链接上时,此函数会更改链接的类以更改颜色,但当我悬停时它们只会更改一次。当我在课堂上不断变化时,我怎样才能做到这一点?

<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>

谢谢

【问题讨论】:

    标签: javascript jquery html css infinite


    【解决方案1】:

    您可以添加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);
    });
    

    【讨论】:

      【解决方案2】:

      如果您想在移动鼠标悬停链接时继续更改类,您只需将事件“hover”更改为“mousemove”:

      https://api.jquery.com/mousemove/

      如果您想在悬停链接但不移动鼠标的同时更改班级,您可以设置一个间隔以保持更改:

      jQuery - How can I continue an animation while the mouse hovers over an element?

      【讨论】:

        【解决方案3】:

        检查下面的 jsFiddle 链接

        Fiddle

        $(".text a").hover(function(e) {
            var evt = e;
            textInterval = setInterval(function() {
        
                var randomClass = getRandomClass();
                $(evt.target).attr("class", randomClass);
        
            }, 10); //change 200 for the timing you want the interval to repeat in ms 
        }, function(e) {
            //clear interval when uses moves mouse away
            clearInterval(textInterval);
            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];
        }
        

        【讨论】:

          猜你喜欢
          • 2021-10-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-12-22
          • 1970-01-01
          • 2012-11-05
          • 1970-01-01
          相关资源
          最近更新 更多