【发布时间】:2017-06-01 10:50:16
【问题描述】:
我的目标: 使用户能够加载模板(包含预设的 jquery、html 和 css)以允许他们单击五个点之一来触发图像上的动画。
我的问题: 当我将多个这些模板加载到我的页面时,我的动画值(在本例中为左边距)应用的次数是页面上存在此模板实例的两倍。如果我的模板被加载两次,margin-left 设置为一个值,跳转到正确的值,然后返回,最后设置正确的值。这意味着,如果我要向页面添加 10 个实例,则需要 20 倍的时间才能获得最后一个值。
在测试之前我认为我的代码是可以的,由于上下文和.once()function,我相信它只会触发一次。
所有 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 实例,但只让函数循环一次。我不确定如何检查这是否已经完成,或者如何确保一旦完成至少一次,就不会再次发生。
:)
【问题讨论】:
-
“我想根据需要添加尽可能多的这个 jQuery 实例”。不,jQuery(或任何其他脚本)只能在呈现给浏览器的任何完整页面中引用一次,无论如何。否则,您将面临您所描述的不可预测行为的风险。
-
@ADyson 我认为我的措辞在那里不正确。我的意思是我想确保这个 jQuery 只添加一次,但承载它的模板可以添加多次。那么有没有办法查看是否已添加该 jQuery 行为或函数,如果已添加,则不要再次加载它?或者再运行一次...
-
我不具体了解 Drupal,但实际代码本身可以在添加自身之前检查具有该名称的行为是否已经存在。
-
@ADyson 有必要检查一下...您知道如何解决这个问题吗?我不确定如何检查该范围内的内容
-
你能检查
Drupal.behaviors.click_the_dots是否已经存在(检查它是否已经是一个对象)?同样,我不知道 Drupal 是如何处理所有这些东西的,但作为一个基本的 JS 原则,你可以检查对象是否存在,这应该告诉你它是否已经被定义。
标签: javascript jquery html drupal jquery-animate