Simulate Hover in jQuery

后端 未结 5 1172
北恋
北恋 2020-12-25 13:33

Currently, I have some jQuery/Javascript code that toggles the css class \'ui-state-hovered\' when a user hovers the mouse over certain elements, and I want to write a test

相关标签:
5条回答
  • 2020-12-25 14:15

    using the console you could try $('#yourelement').trigger('mouseover');

    0 讨论(0)
  • 2020-12-25 14:20

    Write function on hover

    $('.someClass li:first').hover(function(){
          return $(this).attr('class').indexOf('ui-state-hovered') > -1;
    });
    
    0 讨论(0)
  • 2020-12-25 14:30

    Shorthand set mouseenter/mouseleave events

    $(".someClass li:first").hover(
      // Mouse Over
      function(){
        $(this).addClass("ui-state-hovered");
      },
      // Mouse Out
      function(){
        $(this).removeClass("ui-state-hovered");
    });
    

    EDIT

    Set event mouseenter

    $(".someClass li:first").mouseenter(function(){
        $(this).addClass("ui-state-hovered");
      }
    

    Set event mouseleave

    $(".someClass li:first").mouseleave(function(){
        $(this).removeClass("ui-state-hovered");
    });
    

    To simulate mouseover:

    $(".someClass li:first").trigger("mouseenter");
    

    To simulate mouseout:

    $(".someClass li:first").trigger("mouseleave");
    

    To check for a class:

    $(".someClass li:first").hasClass("ui-state-hovered");
    

    To return true if has a class:

    function checkClass(elem, class){
      return $(elem).hasClass(class);
    };
    

    EDIT 2

    I've never use Konacha before, but if I were to take a stab at it using this guide at solitr.com as my guide, I'd say:

    HTML

    <div id="testDiv" class="foo">Some Text</div>
    

    jQuery

    checkClass = function(elem, class){
        return $(elem).hasClass(class);
    };
    

    Konacha

    describe('checkClass', function() {
        it('should be true if elem has class', function() {
            checkClass("#testDiv", "foo").should.be.true;
            checkClass("#testDiv", "bar").should.be.false;
        });
    });
    
    0 讨论(0)
  • 2020-12-25 14:31

    See here

    $('someClass li:first').mouseover();
    

    This should trigger the event

    0 讨论(0)
  • 2020-12-25 14:36

    Try mouseenter and mouseleave

    $('.someClass li:first').mouseenter().mouseleave();
    

    From jQuery docs

    Calling $(selector).hover(handlerIn, handlerOut) is shorthand for: $(selector).mouseenter(handlerIn).mouseleave(handlerOut);

    DEMO: http://jsfiddle.net/skram/wh5N9/

    Try below to check for an class that would have added in hover

    $("#test").mouseenter(function() {
        console.log('Has class hover ' + $(this).hasClass('ui-state-hovered'));
    }).mouseleave(function() {
        console.log('Has class hover ' + $(this).hasClass('ui-state-hovered'));
    })
    

    Make sure the above is registered after .hover

    DEMO: http://jsfiddle.net/skram/wh5N9/2/

    0 讨论(0)
提交回复
热议问题