【发布时间】:2018-11-11 19:04:19
【问题描述】:
我想为在小屏幕尺寸上搜索图像创建类似于谷歌滑块的东西,只需缩小浏览器宽度或从手机访问它,然后在谷歌搜索框中输入“图像”,例如,您将看到 3 张图像在 Google 搜索框下方,您可以滑动以显示更多图片。
因此将有大约 6 张图像彼此相邻,但 2 张完全显示,第三张图像的一半左右,而其他 3 张将被隐藏。
当用户向左滑动第 3 张图像时,其他 3 张图像将变得可见,如果用户已经向左滑动,则应该仍然可以向右滑动以显示第一张图像。
我尝试在谷歌上分析过,但是有些元素我第一次看到,我不知道如何找到相关的JS函数,如果这是用纯JS做的。
这就是我到目前为止所尝试的:
var ImageIndex = 0;
function swipe(event){
var touch = event.targetTouches[0];
var midpoint = Math.floor(screen.width/2);
var px = touch.pageX;
var items = document.getElementsByClassName('image-wrapper');
var itemActive = items[ImageIndex];
if(px < midpoint){
itemActive.style.marginLeft = '-100%';
itemActive.style.transition = '1s';
if (ImageIndex < items.length) {
ImageIndex = ImageIndex + 1;
}else{
ImageIndex = 0;
}
}else{
itemActive.style.marginLeft = '0px';
itemActive.style.transition = '1s';
if (ImageIndex >= 1 ) {
ImageIndex = ImageIndex - 1;
}else{
ImageIndex = 0;
}
}
}
CSS:
.images-gallary{
background-color: #000;
overflow: hidden;
height: 73px;
white-space: nowrap;
}
.image-wrapper{
width: 100%;
display: inline-block;
text-align: center;
}
#secondItem{
background: #fff;
}
HTML:
<div class="images-gallary" ontouchmove="swipe(event)">
<div class="image-wrapper" id="firstItem">
<img class="image" src="http://placehold.it/73/200">
</div>
<div class="image-wrapper" id="secondItem">
<img class="image" src="http://placehold.it/73/300">
</div>
<div class="image-wrapper">
<img class="image" src="http://placehold.it/73/400">
</div>
</div> <!-- .images-gallary -->
这段代码只是滑动前 2 张图片,我得到一个错误:
Uncaught TypeError: Cannot read property 'style' of undefined
那么如何自定义该代码以按顶部所述工作?
我不想使用 Jquery 或任何库,只是纯 JS 代码。
【问题讨论】:
标签: javascript html css