如果元素在 jQuery 中将类从一个特定更改为另一个特定类

If element changed class from one particular to another in jQuery

本文关键字:一个 另一个 jQuery 元素 如果      更新时间:2023-09-26

通常我的幻灯片会自动转到下一张图片,但我想检测它是否通过用户启动的操作(键盘箭头或控件)向后移动。我的解决方案是这样做(我的虚构代码):

if(jQuery("#slideshow article").hasChangedClassFrom("previous").hasChangedClassTo("current")) {
    backwards = true;
}
if(backwards) { // code for backwards
    jQuery("#slideshow article.previous").css("z-index", "1");
    jQuery("#slideshow article.next").css("z-index", "2");
}
else { // code for forwards (normal state)
    jQuery("#slideshow article.previous").css("z-index", "2");
    jQuery("#slideshow article.next").css("z-index", "1");
}

这些类已经实现,因此当前幻灯片始终具有类"current",依此类推。我知道这根本不是有效的代码,但是通过阅读本文,我认为我想要实现的目标会很清楚。我不太擅长JavaScript/jQuery,但我尝试过搜索这样的解决方案,但没有运气。

实时站点//实时 JS 代码

基于上述链接中的代码 http://dans.no/cycle.js

声明一个变量 clickindex=0;

将以下内容放在 jQuery("#slideshow nav a")的点击函数中。click

clickindex = jQuery("#slideshow nav a").index(this);
if(clickindex<index){
    console.log("execute some logic");
}

我的解决方案javascript代码的jsfiddle链接 http://jsfiddle.net/y601tkfL/

不要猜测前一个类,而是使用当前和上一个索引。

http://jsfiddle.net/whyba4L9/5/

更新 2:

var stopp, antall = jQuery("#slideshow article").length;
var index = 0
function slideTo(idx) {
    jQuery("#slideshow article, #slideshow nav a").removeAttr("class").filter(':nth-of-type(' + (idx+1) + ')').addClass("current");
    if(jQuery("#slideshow article:nth-of-type(2)").hasClass("current")) {
        jQuery("#slideshow article:first-of-type").addClass("forrige");
        jQuery("#slideshow article:last-of-type").addClass("neste");
    }
    else if(jQuery("#slideshow article:first-of-type").hasClass("current")) {
        jQuery("#slideshow article:last-of-type").addClass("forrige");
        jQuery("#slideshow article:nth-of-type(2)").addClass("neste");
    }
    else if(jQuery("#slideshow article:last-of-type").hasClass("current")) {
        jQuery("#slideshow article:nth-of-type(2)").addClass("forrige");
        jQuery("#slideshow article:first-of-type").addClass("neste");
    }
    if(index ==antall-1 && idx ==0 )
    {
        //lasto to first
    }
    else if(index>idx || (index == 0 && idx == antall-1))
    {
        alert('BACKWARDS')
    }
    index = idx;
};
function startCycle() {
    stopp = setInterval(function() {
        jQuery("#slideshow article").stop(true, true);
        var idx = index + 1 > antall - 1 ? 0 : index + 1;
        slideTo(idx,false);
    }, 5500);
}; 
if (antall > 1) {
    jQuery("#slideshow").append("<nav>").css("height", jQuery("#slideshow img").height());
    jQuery("#slideshow article").each(function() {
        jQuery("#slideshow nav").append("<a>&bull;</a>");
    }).filter(":first-of-type").addClass("current first");
    jQuery("#slideshow article:nth-of-type(2)").addClass("neste");
    jQuery("#slideshow article:last-of-type").addClass("forrige");
    startCycle();
    jQuery("#slideshow nav a").click(function() {
        clearInterval(stopp);
        startCycle();
        var idx = jQuery("#slideshow nav a").index(this);
        if (index === idx) return;
        slideTo(idx);
    }).filter(":first-of-type").addClass("current");
    jQuery(document).keyup(function(e) {
        if (e.keyCode == 37) {
            var idx = index - 1 < 0 ? antall - 1 : index - 1;
            slideTo(idx);
            clearInterval(stopp);
            startCycle();
        } 
        else if (e.keyCode == 39) {
            var idx = index + 1 > antall - 1 ? 0 : index + 1;
            slideTo(idx);
            clearInterval(stopp);
            startCycle();
        }
    });
}

当用户使用参数 this 更改图像时,请尝试调用此函数。我希望我正确理解了你在问什么。如果没有让我知道,我会重新编码。另外,如果幻灯片放映完成,请发布您的html和javascript。

function whatever(this)
{
  if(this.className == 'previous')
  {
    alert('the user has changed the image');
    this.className = 'current';
  }
  else
  {
    alert('the user hasn''t changed the image');
  }
}

根据我对你的问题的理解,最简单的方法是在索引按钮上放置一个处理程序和一个跟踪当前图像的方法。

聆听幻灯片更改

var currentSlide = '';
$('.slideIndexButtons').on('click', function(e){
    // Conditional logic that compares $(this).data('whichimage') to currentSlide
    var whichImage = $(this).data('whichimage');
    // ->this means attaching data-whichimage="" to each of the elements, or
    // ->you can just stick with detecting the class and going from there
    // Either process results in isBackwards boolean
    if (currentSlide == 'prev' && whichImage == 'current') {
        isBackwards = true;
    }
    if (isBackwards) {
        // Backwards logic here
    } else {
        // Other logic here
    }
    // Unless the event we're listening for in keeping currentSlide updated is also fired when
    // the slide changes due to user input, we'll need to update currentSlide manually.
    currentSlide = whichImage; 
});

跟踪当前幻灯片

$('#slider').on('event', function(){
    // This is assuming that we're strictly listening to the slider's automatic sliding
    // The event you attach this to is either fired before or after the slide changes.
    // Knowing which is key in getting the data you want. You are either getting
    // The data from this slide $(this).data('whichimage') or 
    // $(this).next().data('whichimage')
    // Again, you can go with classes, but it is a lot of logic which you have to 
    // update manually if you ever have to add or alter an image in the slide set.
    // Either way, you end up with the variable targetImage
    currentSlide = targetImage;
});

如果幸运的话,您的幻灯片代码有一个 API,可让您侦听何时触发与幻灯片相关的事件。否则,您必须找到一种方法来手动设置、触发和侦听这些事件,无论是通过传入的回调还是通过 (eek!) 更改代码并可能无意中更改其功能。

应该给你你想要的。让我知道它是怎么回事。

您可以在循环中的 slideTo 函数的最开头添加此行.js

if((idx < index && !(idx == 0 && index == antall - 1)) ||
   (idx == antall - 1 && index == 0)){
   jQuery.trigger('BACKWARDS')
}

然后在其他方便的地方为"BACKS"添加一个事件处理程序(也许在循环结束时.js?

jQuery.on('BACKWARDS', function(e){
   //DO THINGS HERE
}

我写了一个插件attrchange,我认为这将有效地解决你的问题。 attrchange是一个简单的jQuery插件,用于检测属性更改。插件内部基于浏览器使用以下兼容方法之一来检测属性更改,

  • 突变观察者
  • DOMAttrModified
  • 在财产上更改

尝试下面的演示,以了解有关如何使用该插件以满足您的需要的更多信息。

点击阅读更多关于吸引力的信息。

注意:该插件不使用轮询,因此您可以放心使用它,但是支持轮询作为插件的扩展。如果您有兴趣,可以阅读更多内容。

$('#test').one('click', function() {
  $('#test').attrchange({
    trackValues: true,
    callback: function(event) {
      $('#result').html('<div><label>Attribute Name: </label>' + event.attributeName + '</div>' + '<div><label>Old Value</label>' + event.oldValue + '</div>' + '<div><label>New Value</label>' + event.newValue + '</div>');
    }
  });
  //this will toggleClass 'blue-background' every 2 secs
  setInterval(function() {
    $('#test').toggleClass('lightblue-background');
  }, 2000);
});
html {
  font-family: Segoe UI, Arial, sans-serif;
  font-size: 13px;
}
div#test {
  border: 1px solid #d2d2d2;
  padding: 10px;
  display: inline-block;
}
.lightblue-background {
  background-color: #DBEAF9;
}
div label {
  font-weight: bold;
  margin-right: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/meetselva/attrchange/master/js/attrchange.js"></script>
<div id="test">
  <p style="font-weight: bold;">Click anywhere in this box to Start the DEMO</p>
  <p>The demo is to simply toggle a class 'lightblue-background' to this div every 2 secs.</p>  
  <div id="result" style="font-size: 0.9em;"></div>

使用插件查看您的案例的伪代码,

jQuery("#slideshow article").attrchange({
   trackValues: true,
   callback: function(event) {
      if ($(this).hasClass('current') && 
         (event.oldValue && event.oldValue.indexOf('previous') >= 0)) {
         //code for backward
      } else {
         //code for forward
      }
   }
});