简体   繁体   中英

sliding logos - best way

I am creating event's page and at the bottom I placed many logos. It sliding from right to left. I don't use jQuery, only pure Javascript and I just wondering about the best performance. My code works, but maybe there is better way to do that ? I think this 'animation' sometimes slow down.

var banners = [],
    links = [];

links[0] = 'http://...',
banners[0] = 'img/logo1.png',
...

var banLenght = banners.length,
    banContent = "<div id='bannersBack'><div id='banners' style='display:inline-block;'>";

for (var ii =0; ii < banLenght; ii++){
    banContent += "<a target='_blank' href='"+links[ii]+"'><img src='"+banners[ii]+"'></a>";
}
banContent += "</div></div>";
document.getElementById('sliding-logos').innerHTML = banContent;

var actual = document.getElementById('banners');
var move = function(){
    position = actual.offsetLeft;
    position -= 1;
    actual.style.left = position +"px";

    // 3000 is sum of banner's width                
    if (position > -3000) { 
        setTimeout( move, 20);
    }else {
        actual.style.left = "0px";
        move();
    }
};
move();

Best performance is achieved by using CSS transforms+translate. Modern browsers will be able to use the GPU to do the transformation.

.animation {
    transition: .25s ease-in-out;
    transition-property: transform, width;
}
.move {
    width: 200px;  // set width to 200px
    translateX(-200px); // move 200px to the left (always relative)
}

Typically, if you move large images or large DOM Nodes, you will see some stuttering. With CSS transform you get no stuttering.


If you can't use CSS transform (because you need it to work in IE8 or lower) I'd use jQuery's .animate .

  • single image sprite rather than multiple image
  • CSS Transitions rather than JS. CSS is part of the browser engine and doesn't have to modify the properties of the DOM so it should be faster

Here's an example (however it is does NOT work in all browsers yet) http://css-tricks.com/infinite-all-css-scrolling-slideshow/

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