我使用jQuery编写了一个非常简单的滑块。它的工作原理是对子img元素进行计数和编号,并显示与计数器变量相对应的img,该变量随着用户按下"右键而变化。如果"离开"按钮并减少按下按钮。它工作正常,除非页面上有多个实例。(我认为因为变量是全局的)
一个按钮最终控制所有滑块的流动。此外,一次只有一个滑块会显示图像,因为它们都会引用相同的变量。
有没有办法让滑块的每个实例都有自己的计数器($ n)和幻灯片编号($ slide)变量?
以下是我所拥有的内容:http://jsfiddle.net/Mn4jk/2/(虽然没有实际图片)
这是直接的html和jQuery
HTML:
<div>
<img src="../graphics/arrow_left.png" class="left" alt="left">
<img src="../graphics/arrow_right.png" class="right" alt="right">
<div class="carousel">
<img src="../graphics/img1.png" alt="1">
<img src="../graphics/img2.png" alt="2">
<img src="../graphics/img3.png" alt="3">
</div>
</div>
jQuery的:
$(window).ready(function () {
var $n = 0;
var $slides = $('.carousel img').length - 1;
$('.right').click(function () {
if ($n <= ($slides - 1)) {
$('.carousel img').eq($n).fadeOut('400');
$n++;
$('.carousel img').eq($n).delay('400').fadeIn('400');
} else {
$('.carousel img').eq($slides).fadeOut('400');
$n = 0;
$('.carousel img').eq(0).delay('400').fadeIn('400');
}
});
$('.left').click(function () {
if ($n >= 1) {
$('.carousel img').eq($n).fadeOut('400');
$n--;
$('.carousel img').delay('400').eq($n).fadeIn('400');
} else {
$('.carousel img').eq(0).fadeOut('400');
$n = ($slides)
}
$('.carousel img').delay('400').eq($n).fadeIn('400');
});
$('.carousel img').eq($n).fadeIn('400');
});
我知道我可以复制代码并创建一个新类,但我更倾向于一个允许在一个页面上使用任意数量的滑块的解决方案。
答案 0 :(得分:0)
是的,Javascript具有允许此功能的“类”。类可以多次实例化,每个实例都有自己的变量,方法等。类是“面向对象编程”(OOP)的关键构建块。
有关更多信息,请在Google上搜索“Javascript课程”。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript
注意:有多种方法可以定义Javascript类。所以那里的教程将展示不同的方法。
我很佩服建立自己的意愿和愿望。但是,有很多库都有这个功能(只需搜索Javascript库)。
示例JSFiddle作为类:http://jsfiddle.net/Mn4jk/4/
var Slider = function(element) {
this.$n = 0;
this.img = element.find(".carousel img");
this.$slide = this.img.length-1;
this.left = element.find(".left");
this.right = element.find(".right");
this.buttons();
this.img.eq(this.$n).fadeIn('400');
}
Slider.prototype.buttons = function() {
var that = this;
this.right.click(function () {
if (that.$n <= (that.$slide - 1)) {
that.img.eq(that.$n).fadeOut('400');
that.$n++;
that.img.eq(that.$n).delay('400').fadeIn('400');
} else {
that.img.eq(that.$slide).fadeOut('400');
that.$n = 0;
that.img.eq(0).delay('400').fadeIn('400');
}
});
this.left.click(function () {
if (that.$n >= 1) {
that.img.eq(that.$n).fadeOut('400');
that.$n--;
that.img.delay('400').eq(that.$n).fadeIn('400');
} else {
that.img.eq(0).fadeOut('400');
that.$n = (that.$slide);
}
that.img.delay('400').eq(that.$n).fadeIn('400');
});
};
$(window).ready(function () {
var slider1 = new Slider(jQuery("#slider-instance"));
});