所以我正在尝试在 jquery 中制作一个简单的画廊查看器。
我的代码中有这样的东西:
<div class="photoset">
<img />
<img />
</div>
<div class="photoset">
<img />
<img />
<img />
</div>
我希望在显示第一张图片时隐藏其他图片,如果我单击图片的右半边,则显示下一张图片。
这是我目前所得到的:
$(document).ready(function () {
var counter = 0,
$items = $('.photoset figure'),
numItems = $items.length;
var showCurrent = function () {
var itemToShow = Math.abs(counter % numItems);
$items.removeClass('show');
$items.eq(itemToShow).addClass('show');
};
$("div").click(function (e) {
var pWidth = $(this).innerWidth();
var pOffset = $(this).offset();
var x = e.pageX - pOffset.left;
if (pWidth / 2 > x) {
counter--;
showCurrent();
}
else {
counter++;
showCurrent();
}
});
});
点击功能有效,但它改变了所有的 div,我认为计数器没有像我希望的那样工作。
这是生成图库的代码:
@foreach (var item in Model)
{
<br />
@Html.DisplayFor(modelitem => item.NomeGaleria)
<br />
<div class="photoset">
@{ var item2 = item.FilePaths;}
@for (var k = 0; k < Enumerable.Count(item2); k++)
{
<br />
<figure class="@(k == 0 ? "show" : "" ) ">
<img src="~/images/@Html.DisplayFor(modelItem2 => item2[k].FileName)" alt="" height="300" width="500" />
</figure>
<br />
}
</div>
抱歉,如果答案很明显,我对 jQuery/JavaScript 非常陌生。
最佳答案
试试看:
HTML:
<div class="photoset">
<img src="http://inspirebee.com/wp-content/uploads/2013/04/animal-fashion-parade.jpg" />
<img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals18.jpg" />
<img src="http://inspirebee.com/wp-content/uploads/2013/04/animal-in-fashion.jpg" />
<img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals20.jpg" />
</div>
<div class="photoset">
<img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals26.jpeg" />
<img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals14.jpg" />
<img src="http://inspirebee.com/wp-content/uploads/2013/04/animal-fashion.jpg" />
<img src="https://framboisemood.files.wordpress.com/2013/04/fashion-zoo-animals13.jpg" />
<img src="http://www.fubiz.net/wp-content/uploads/2013/03/Fashion-Zoo-Animals9.jpg" />
</div>
CSS:
.photoset > img:not(:first-child) {
display: none;
}
JavaScript:
$(document).ready(function() {
$('.photoset').each(function(){
$(this).data('counter', 0);
});
var showCurrent = function(photoset) {
$items = photoset.find('img');
var counter = photoset.data('counter');
var numItems = $items.length;
var itemToShow = counter % numItems;
$items.hide();
$items.eq(itemToShow).show();
};
$('.photoset').on('click', function(e) {
e.stopPropagation();
var photoset = $(this);
var pWidth = photoset.innerWidth();
var pOffset = photoset.offset();
var x = e.pageX - pOffset.left;
if (pWidth / 2 > x) {
photoset.data('counter', photoset.data('counter') - 1);
showCurrent(photoset);
} else {
photoset.data('counter', photoset.data('counter') + 1);
showCurrent(photoset);
}
});
});
JSFiddle:https://jsfiddle.net/ty0vqk2y/1/
关于javascript - jQuery - 试图让一个函数与多个相同的类、div 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34930076/