【发布时间】:2018-02-28 18:19:04
【问题描述】:
我想创建带有缩略图的简单产品滑块。虽然可能有超过 3 个缩略图,但我只想显示其中的 3 个。通过单击“更多”按钮,我的目标是隐藏第一张已经可见的图像,并通过更改它们的类从隐藏图像中显示一个。
在 hiddenImages[0] 之前代码运行良好。 Firefox 控制台给出以下错误:“TypeError: hiddenImages[0] is undefined”
我做错了什么?
// All images
var images = $('[data-image]');
// Click for more images
var more = $('.more');
// Add show class to all images
images.each(function(index, element){$(this).parent().addClass('visible')})
// Hide images begining from 4th image
images.each(function(index, element){if($(this).data('image') >= 4)
{$(this).parent().removeClass('visible').addClass('hidden')} })
// Show big image when clicking thumbnail
images.each( function(index, element){
$(this).click(function(){ $('#pic img').attr('src', $(this).attr('src')) }) })
// Hide 1st from visible images and show first from hidden images
more.on('click', function(){
// Find all hidden images and remove visible class from first one
hiddenImages = images.hasClass('hidden');
hiddenImages[0].removeClass('visible').addClass('hidden');
})
#pic {
width: 300px;
height: 300px;
border: 1px solid #ccc;
margin-right: 5px;
float: left;
}
.thumbnails {
height: 300px;
width: 50px;
padding:0;
margin:0;
margin-right: 10px;
float: left;
}
.thumbnails li {
display: inline;
list-style: none;
float: left;
width: 70px;
height: 70px;
margin-bottom: 5px;
border:1px solid #ccc;
text-align: center;
}
.thumbnails li img {
width: 70px;
height: 70px;
cursor: pointer;
}
.more {
display: inline;
list-style: none;
float: left;
width: 70px;
height: 70px;
margin-bottom: 5px;
border:1px solid #ccc;
text-align: center;
}
.hidden {display: none!important;}
.visible {display: block!important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="holder">
<div id="pic">
<img src="https://placeimg.com/300/300/nature">
</div>
<ul class="thumbnails">
<li><img data-image="1" src="https://placeimg.com/300/300/nature"></li>
<li><img data-image="2" src="https://placeimg.com/300/300/any"></li>
<li><img data-image="3" src="https://placeimg.com/300/300/animals"></li>
<li><img data-image="4" src="https://placeimg.com/300/300/sepia"></li>
<li><img data-image="5" src="https://placeimg.com/300/300/grayscale"></li>
<li><img data-image="6" src="https://placeimg.com/300/300/tech"></li>
<li class="more">MORE</li>
</ul>
</div>
【问题讨论】:
-
get(0) 给出另一个错误“TypeError: hiddenImages.get is not a function”
-
哦,是的,那是因为
.hasClass()返回一个布尔值。 -
看来你应该简化你的整体策略。既然缩略图似乎是固定大小的,为什么不只是有一个固定大小的容器,只允许 3 个可见并隐藏溢出。那么就只需要调整容器内容的位置即可。
-
TypeError: hiddenImages.first 不是函数
标签: javascript jquery arrays css