javascript - 当鼠标在框上时停止动画并在鼠标移出时将其动画回来,不起作用

标签 javascript jquery html css django

我有一个图像列表,这些图像在一个 html 页面中并排显示在一个 div 中。当有很多图片强制展开div时,div会自动从左向右滚动,反之亦然。

当用户将光标放在那个 div 上时,动画应该停止,当光标离开时,动画应该重新开始。但它不起作用,有时会停止,有时不会。

HTML 由 django 呈现

<div class="row" style="position: relative;">
    <div id='mainDiv' class="col-sm-12" style="">
         <h1">Title</h1><hr>
         <div style="overflow:hidden;white-space: nowrap;">

             {% for img in all_images %}
                 <div class="" style="height:200px;display:inline-block"> 
                 <img height="100" title="" src="{{img.scr}}"> 
                 </div>      
             {% endfor %}

         </div>
    </div>
</div>

JS

function animatethis(targetElement, speed) {
            var scrollWidth = $(targetElement).get(0).scrollWidth;
            var clientWidth = $(targetElement).get(0).clientWidth;
            $(targetElement).animate({ scrollLeft: scrollWidth - clientWidth },
            {
                duration: speed,
                complete: function () {
                    targetElement.animate({ scrollLeft: 0 },
                    {
                        duration: speed,
                        complete: function () {
                            animatethis(targetElement, speed);
                        }
                    });
                }
            });
        };
        var sec = 20000;
        animatethis($('#mainDiv'), sec);

        $("#mainDiv").hover(function(){
            $(this).stop(true)
        });
        $("#mainDiv").mouseout(function(){
            animatethis($(this), sec);
        });

最佳答案

--- <div id="mainDiv" class="col-sm-12" style="">
+++ <div class="col-sm-12" style="">
---   <div style="overflow:hidden;white-space: nowrap;">
+++   <div id="mainDiv" style="overflow:hidden;white-space: nowrap;">

容器组件中有 mainDiv id 标签。那不是您要设置动画的 div。

这是一个有效的:https://codepen.io/anon/pen/KxgdWO

关于javascript - 当鼠标在框上时停止动画并在鼠标移出时将其动画回来,不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52067798/

相关文章:

javascript - PDF.JS - 检测页面何时呈现

javascript - 如何清除客户端中服务器端数据表的行

javascript - html5 canvas绘制多条线

javascript - 如何使用 jQuery 或 Javascript 沿对 Angular 线滚动

html - 如何将图像放置在图像上?

javascript - 如何在文本中添加省略号

javascript - 如何通过添加内部单引号来打印可变数据和字符串

javascript - jQuery - 循环遍历 TD 宽度,然后循环遍历 TH 并应用 TD 宽度

javascript - 在 anchor 上单击停止重定向页面并显示警报消息

javascript - If 语句给出不正确的结果。