Scrolling marquee javascript image

Currently, I want to make selection of several images, but my code only allows one. Did you know that I could add multiple images to this code? (I already tried to add images directly to the div element inside the body - it does not work.)

<style type="text/css"> <!-- #container { background-image: url(images/avycopy.jpg), url(images/5mwmcp.jpg); height:428px; width:284px; background-repeat:repeat-x; background-size:284px 428px; background-position: top left, top right; } --> </style> <script type="text/javascript"> <!-- var p=0; var speed=20; // vary this to suit, larger value - slower speed window.onload=function() { gallery(); } function gallery() { document.getElementById('container').style.backgroundPosition=p+'px 0'; p--; //change this to p-- for right to left direction setTimeout('gallery()',speed); } //--> </script> 
+6
source share
1 answer

I put such a slider for you. No frameworks are required, although there are some cross-browser issues that I have not dealt with (including IE prior to version 8, relating to scrollWidth differently).

First arrange the code like this:

 <div id="marquee-container" ><span><img src="http://www.dragonfly-site.com/graphics/20-free-dragonfly-clip-art-l.jpg" /></span ><span><img src="http://0.tqn.com/d/macs/1/0/2/M/-/-/clipprojectchristmas_400x400.png" /></span ></div> 

Add some CSS as follows:

 #marquee-container { width: 500px; /* or whatever you want */ margin: 0 auto; /* centers it */ overflow: hidden; white-space: nowrap; } 

Now all that needs to stay is javascript to keep it moving. This will return to the beginning as soon as it scrolls all the way; it should look continuous as it duplicates all the images at the end:

 (function(window, document, undefined) { var spaceinterval = 1; var timeinterval = 10; // `speed` var max; var firstrun = true; // Interval function: var gallery = function() { var elem = document.getElementById("marquee-container"); if (elem) { if (firstrun) { max = elem.scrollWidth; // Clone the children of the container until the // scrollWidth is at least twice as large as max. while (elem.scrollWidth < max * 2) { var length = elem.children.length; for (var i = 0; i < length; ++i) { elem.appendChild(elem.children[i].cloneNode(true)); } break; } firstrun = false; } if (elem.scrollLeft >= max) { elem.scrollLeft -= max; } else { elem.scrollLeft += spaceinterval; } } }; window.setInterval(gallery, timeinterval); })(window, document); 

In jsfiddle

+6
source

Source: https://habr.com/ru/post/903299/


All Articles