我在jQuery中制作了幻灯片,现在我希望在页面上有2个幻灯片,我怎样才能使我的功能可以重复使用,这样两张幻灯片就不会相互冲突?
这是我的Js代码。
jQuery(document).ready(function ($) {
var slideCount = $('.slidek ul li').length;
var slideWidth = $('.slidek ul li').width();
var slideHeight = $('.slidek ul li').height();
var screenWidth = $( window ).width();
var sliderUlWidth = slideCount * screenWidth;
$('.lists').css({ width: screenWidth});
$('.slidek').css({ maxWidth: screenWidth, height: "auto" });
$('.slidek ul').css({ width: sliderUlWidth, marginLeft: - screenWidth });
$('.slidek ul li:last-child').prependTo('.slidek ul');
function moveLeft() {
$('.slidek ul').animate({
left: + slideWidth
}, 200, function () {
$('.slidek ul li:last-child').prependTo('.slidek ul');
$('.slidek ul').css('left', '');
});
};
function moveRight() {
$('.slidek ul').animate({
left: - slideWidth
}, 200, function () {
$('.slidek ul li:first-child').appendTo('.slidek ul');
$('.slidek ul').css('left', '');
});
};
$('a.control_prev').click(function () {
moveLeft();
});
$('a.control_next').click(function () {
moveRight();
});
});
这将是幻灯片的HTML结构。
<div class="slidek">
<a href="javascript:void(0);" class="control_next"></a>
<a href="javascript:void(0);" class="control_prev"></a>
<ul>
<li class="lists">
<div class="testimonial_container">
<img src="****.png">
<h2>John Doe</h2>
</div>
</li>
<li class="lists">
<div class="testimonial_container">
<img src="****.png">
<h2>John Doe</h2>
</div>
</li>
</ul>
</div>
jsfiddle:https://jsfiddle.net/zbqe2w93/
答案 0 :(得分:2)
将您的幻灯片显示为jquery插件。
然后你可以随心所欲地使用它。
有一种简单的方法可以创建自己的插件,你可以在这里参考。
答案 1 :(得分:2)
你会想要研究创建一个jquery插件模式,使事情更容易重复,但是为了方便起见和jquery开始(我假设你,如果你不是,请道歉)我会工作你有什么。你的代码中有很多可疑的东西,但是我会尝试回答手头的问题,而不会偏离其他地区,并像一个狂热者一样行事。
您需要考虑jQuery上下文。目前,您使用相同的选择器定位页面中的所有元素,因此(例如)当您单击右箭头时,它将更改页面上的所有滑块。
通常,您定位容器的父级,然后使用它来查找其中的元素并绑定和引用它们。您还可以创建对元素的引用,这样您就不会在每次想要更改它们时都尝试找到它们。
注意这是一种反模式,但这是我在学习时的开始,例如(只是一个样本)
$('.slidek').each(function() {
var $container = $(this), // get the container for this iteration. The prefix is just to show it's a jquery element
$slider = $('ul', $container), // this refers to only the ul within the container
$rightArrow = $('a.control_prev', $container); // only the right arrow within the container
function moveRight() {
// do your moveRight code referencing $slider
// also "this" used here will reference the anchor you clicked
// this can be handy if you want to combine the left/right functions
// because the left/right code has a very similar structure
$slider.animate......
}
$rightArrow.click(moveRight); // attach event to only the this arrow
});
正如我之前提到的,这不是最好的做法,但它应该适合你,而不必重写一大堆代码。我会尝试挖掘一些我喜欢的样本模式,或者如果有人可以在评论中添加一些内容。我建议你做一些关于jQuery插件的阅读,只要注意你现在阅读的大部分内容可能会建议你需要安装3种口味的grunt / gulp并使用require模块等。只需回到基础并学习那里。
找到此https://github.com/jquery-boilerplate/jquery-patterns。它看起来很古老,但是又一次,jQuery也是如此。