我的目标: 要使用户能够加载模板(包含预设的jquery,html和css),以允许他们单击五个点中的一个来触发图像上的动画。
我的问题: 当我将多个这些模板加载到我的页面时,我的动画值(在这种情况下为margin-left)应用的倍数是页面上有此模板实例的两倍。如果我的模板加载了两次,则margin-left设置为一个值,跳转到正确的值,然后在最终设置正确的值之前返回。这意味着如果我要向页面添加10个实例,那么获取最后一个值需要20倍。
在测试之前我认为我的代码没问题,因为上下文和.once()
函数,我相信它只会触发一次。
所有html和CSS都按预期运行,只是jQuery是个问题。
我的代码:
(function ($) {
Drupal.behaviors.click_the_dots = {
attach: function (context, settings) {
$('.wrapper_class', context).once('click_the_dots', function () {
// Prevent other buttons from being clickable until the
// previous animation is complete.
var animationDone = false;
function clickDots(dotNum) {
$('.dot_class_num_' + dotNum).click(function () {
// Setup context, to keep animations to the container in which the dots exist.
var findElem = $(this).parent().parent().parent().find('.inner_wrapper');
// Prevent other buttons from being clickable until the
// previous animation is complete.
if (animationDone === false) {
animationDone = true;
// Find the visible image.
var animatingImage = findElem.find('.dot_class_num_active');
// Find the image that will be animating in.
var thisImageAnim = findElem.find('.dot_num_img_src_' + dotNum);
if (animatingImage.is(thisImageAnim)) {
// Can't click on the same dot again, until another dot is clicked.
animationDone = false;
return;
} else {
// Animate out the already visible image.
// Remove the visible image class as it's going to be hidden.
findElem.find('.dot_class_num_active').removeClass('dot_class_num_active');
// Animate it to hide to the left.
animatingImage.animate({
marginLeft: '-10%',
opacity: 0
}, 280, 'easeInOutQuad');
// Animate in the image associated with the dot click
// Set the image css to be further right in order to animate to left at 0.
thisImageAnim.css('margin-left', '10%').delay(200).animate({
marginLeft: '0',
opacity: 1
}, 300, 'easeInOutQuad', function () {
// Set the now visible image to the visible image.
thisImageAnim.addClass('dot_class_num_active');
}).promise().done(function () {
// Now allow the other dots to be clicked.
animationDone = false;
});
}
}
});
}
// For each of the five dots.
for (i = 1; i <= 5; i++) {
clickDots(i);
}
});}};})(jQuery);
我想根据需要添加这个jQuery的尽可能多的实例,但只能将函数循环一次。我不确定如何检查这是否已经完成,或者如何确保一旦完成至少一次,就不应该再次发生。
:)