0

我正在尝试使用 jQuery 创建一个图像查看器,但遇到了一个到目前为止我无法解决的问题。图像查看器非常基本,顶部有一个大图像,下面有 6 个小图像。当用户单击其中一个小图像时,大图像 src 会变为小图像的 src。此外,还有一个按钮,单击该按钮可动态添加新的小图像。所有这些都可以正常工作。

问题出现在我决定添加滚动效果后,以便在生成新图像时页面自动向下滚动以便您可以看到它。这使用户不必手动执行此操作。我已经让它工作了,但它似乎在某些情况下会导致手动滚动问题。我的意思是有时在我添加图像并向下滚动到它之后,我无法使用鼠标滚轮手动向上滚动。

有时它确实会响应鼠标滚轮,但只有在可能持续 1-20 秒的延迟之后。当它不响应鼠标滚轮时,我尝试使用侧面滚动条,这有时会起作用,有时会卡住,不允许我向上或向下。我发现如果我一张一张地添加图像,等待它们完全加载,那么通常不会有任何问题。但是,如果我继续快速连续按下添加新图像按钮,那么问题似乎就出现了。我还发现,如果我等待足够长的时间,问题似乎就会消失,这让我认为这是因为我的滚动效果太慢了,而且我的浏览器必须等待它完成,直到它让我手动滚动。

我曾考虑在按下添加图像按钮后禁用它,以便可以加载新图像并且可以在添加另一个新图像之前进行滚动,但我希望有另一种解决方案。

任何帮助或方向将不胜感激。谢谢

链接到现场演示

HTML

<div id="container">

    <button>Add<br>Images</button>

    <div id="large-image-wrap">
        <img src="http://bilal.cu.cc/images/profile_covers/profile_cover36.jpg">
    </div>

    <div id="small-images-wrap" class="clearfix">
        <div class="si-box"><img src="http://bilal.cu.cc/images/profile_covers/profile_cover36.jpg"></div>
        <div class="si-box"><img src="http://bilal.cu.cc/images/profile_covers/profile_cover64.jpg"></div>
        <div class="si-box"><img src="http://bilal.cu.cc/images/profile_covers/profile_cover44.jpg"></div>
        <div class="si-box"><img src="http://bilal.cu.cc/images/profile_covers/profile_cover45.jpg"></div>
        <div class="si-box"><img src="http://bilal.cu.cc/images/profile_covers/profile_cover31.jpg"></div>
        <div class="si-box"><img src="http://bilal.cu.cc/images/profile_covers/profile_cover65.jpg"></div>
    </div>

</div>

CSS

#container{
width:960px;
margin:0 auto 20px auto;
position:relative;
}

button{
position:fixed;
margin-left:-105px;
margin-top:19px;
width:100px;
text-transform:uppercase;
text-align:center;
font-weight:bold;
}

#large-image-wrap{
width:960px;
height:320px;
position:fixed;
z-index:10;
}

#large-image-wrap img{
width:100%;
height:auto;
border-top:20px solid white;
border-bottom:13px solid white;
}

#small-images-wrap{
width:960px;
position:relative;
top:353px;
}

.si-box{
width:32%;
height:auto;
float:left;
margin-bottom:1%;
}

.si-box img{
width:100%;
height:auto;
}

div.si-box:nth-child(2), div.si-box:nth-child(3n+2){
margin:0 2%;
}

jQuery

$(document).ready(function(){

    var imgNum = 1; 

    // Add new image
    $("button").on("click", function(){
        if(imgNum > 70){imgNum = 1};
        $("#small-images-wrap div:last-of-type").after('<div class="si-box"><img src="http://bilal.cu.cc/images/profile_covers/profile_cover'+ imgNum +'.jpg"></div>');
        imgNum++;

        // Scroll to added image
        $('html, body').animate({scrollTop: $("#small-images-wrap div:last-of-type").offset().top}, 2000);
    });

    // On click effect
    $(document).on('click', '.si-box img',  function () {
        var $imgSrc = $(this).attr("src");
        $("#large-image-wrap img").attr("src", $imgSrc);
    });

}); // Document Ready End
4

0 回答 0