简体   繁体   中英

JQuery .animate() only works in Chrome

I am using the JQuery .animate() function to slide divs in a container div. This works without issue in Google Chrome, but when I try in either Firefox or IE, the divs become a garbled mess and don't actually slide. I'm new to Javascript and ignorant in the ways of browser compatibility, can anyone point me in the right direction? Here is the relevant code:

The HTML

<div id="slider">
  <div id="main" class="content">
  </div>

  <div id="projects" class="content">
  </div>

  <div id="about" class="content">
  </div>

  <div id="contact" class="content">
  </div>
</div>

The CSS

#slider {
  width: 100px;
  height: 100px;
  overflow: hidden;
  position: relative;
}

#main {
  background-color: red;
  width: inherit;
  height: inherit;
  position: absolute;
}

#projects {
  background-color: blue;
  width: inherit;
  height: inherit;
  position: absolute;
}

#about {
  background-color: yellow;
  width: inherit;
  height: inherit;
  position: absolute;
}

#contact {
  background-color: green;
  width: inherit;
  height: inherit;
  position: absolute;
}

.content {
  left: 0;
  top: 0;
}

The JavaScript

$(document).ready(function() {

var contentWidth = '100px';

for( var i=0; i < 2; i++) {
  $('.gallery' + (i + 1)).colorbox({ opacity:0.5 , rel:'gallery' + (i+1)});
}

$('.content').css({
  position: 'absolute',
  left: contentWidth
});

$('#main').addClass('visible');
document.getElementById('main').style.left = "0";

$("li a").click(function () {
  event.preventDefault();
  var $blockID = $( $(this).attr('href') );

  if ($blockID.hasClass('visible')) { return; }

  $('.content.visible')
    .removeClass('visible')
    .animate({ left: '-=100px' }, {  
      duration: 'slow',
      complete: function () {
        $(this).css('left', '100px');
      }
    }
 );

$blockID
  .addClass('visible')
  .animate({ left: 0 }, {duration: 'slow'});
});

});

JSFiddle: http://jsfiddle.net/bwvVZ/

I can also provide a link to the site in question, although I will hold off because I am not sure if its against the rules. Any help is much appreciated!

You are missing the event argument from your click handler

$("li a").click(function(){ 
    event.preventDefault();
    //...
});

It should be

$("li a").click(function (event){
    event.preventDefault();
    //...
});

DEMO .

Can't test in IE myself but this fixes Firefox and the returnValue should fix IE. CSSDeck Test - I can't access jsfiddle from my current location.

$("li a").click(function (event){
    event.returnValue = false; //ie
    if(event.preventDefault) //prevents error if not found
        event.preventDefault();

    var $blockID = $($(this).attr('href'));

    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM