元素链接:click here
fiddle 链接:click here
我有一个我的客户想要使用的 slider ,没有任何插件。
涉及的html如下:
涉及的js/jQuery如下:
主要涉及的js部分如下:
var newSliderWidth = $('#oCarol').width(); // container width is recalculated and updated
liW = newSliderWidth; // new li width
liFW = (liW * $slider.find('li').length); // new width is calculated for the container
$('.panel-inner li').css('width', liW); // new width is assigned to the li(s)
$slider.width(liFW); // new width is assigned to the container
$('.button a').on('click', function (e) { // this determines the left and right buttons' functionality
e.preventDefault(); // prevent the default
if (!animating) {
var left = Math.abs(parseInt($slider.css('left'))); // find the current slider position
// 'side' is the amount of distance in pixels that the slider needs to move whenever a left or right arrow is pressed, respectively
var side = ($(this).data('direction') == 'right') ? (((left + (liW * iXS)) >= liFW) ? 0 : -(left + liW)) : ((left > 0) ? -(left - liW) : -(liFW - (liW * iXS)));
rotate(side);
console.log('Current position is: '+side);
}
});
// whenever a screen resize happens, the slider moves to the first slide
$('.panel-inner').animate({
left: 0
});
目前,无论何时发生屏幕大小调整,我都必须将 slider 重置为第一张幻灯片,否则当前幻灯片位置会变得困惑,显示一半,同时显示下一张幻灯片的一半,在同时。
我需要的是,以某种方式正确显示当前幻灯片,这样我就不必将 slider 位置重置为“left: 0px”
这是一个例子,当我评论我将'.panel-inner'重置为'left:0'的代码时会发生这种情况:
最佳答案
首先,您应该移动绑定(bind)按钮点击处理程序的代码,使其位于窗口调整大小处理程序之外。随着窗口大小的调整,您将一遍又一遍地重新绑定(bind)这些点击处理程序。
其次,我认为您的代码过于复杂。我认为跟踪当前显示的面板的索引并具有根据索引滑动到面板的功能更容易。
请注意,我使用“margin-left”css 属性来进行滑动,而不是“left”。这就是我以前看到的实现滑动的方式,但我并不是说一种方式比另一种方式更好。
这是它的样子:
$(function() {
var animating = false,
$container = $('.panel'),
$slider = $('.panel-inner'),
$panels = $slider.children(),
currentPanelIndex = 0,
panelWidth,
resizeTimerId = null;
function slideTo(panelIndex) {
animating = true;
$slider.stop(true, true).animate({
"margin-left": -(panelIndex * panelWidth)
}, 1000, function () {
animating = false;
currentPanelIndex = panelIndex;
});
}
function resizeSlider() {
panelWidth = $container.width();
$panels.css('width', panelWidth);
$slider.width(panelWidth * $panels.length);
$slider.css({ "margin-left": -(currentPanelIndex * panelWidth) });
}
$(window).on('resize', function() {
clearTimeout(resizeTimerId);
resizeTimerId = setTimeout(function () {
resizeSlider();
}, 100);
});
$('.button a').on('click', function(e) {
e.preventDefault();
if (!animating) {
var direction = $(this).data('direction');
var panelIndex = currentPanelIndex + ((direction == 'right') ? 1 : -1);
if (panelIndex < 0) {
panelIndex = $panels.length - 1;
} else if (panelIndex > ($panels.length - 1)) {
panelIndex = 0;
}
slideTo(panelIndex);
}
});
resizeSlider();
});
注意:它可以在调整窗口大小时调用 slideTo(currentPanelIndex)
进行调整,但随后它会被动画化,如果用户继续调整大小,动画将排队。
关于javascript - 计算 slider 位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29903512/