With the development and popularity of Internet advertising, website advertising space has become one of the important entrances to various websites. How to achieve a beautiful and practical advertising carousel effect on the website has also become an important issue that website developers pay attention to. In this article, we will introduce a JavaScript-based implementation method of advertising image carousel.
1. Basic principles of carousel
Image carousel refers to automatically or manually switching images on a web page within a certain time interval, thereby looping through multiple images to achieve display Multiple information purposes. To implement this function, JavaScript needs to be operated.
JavaScript itself is an event-based language that triggers code execution through various events on the page that interact with users (such as mouse clicks, mouse hovers, keyboard events, etc.). In carousel images, we can associate image switching buttons, image switching time intervals, transition effects between images, etc. with JavaScript events to achieve automatic scrolling and manual operation of images.
2. Technical details of carousel implementation
Based on the above basic principles of carousel, the specific implementation technical details are introduced below.
- Layout design
First design a container element, with multiple image elements nested inside the container element. Image elements use the same style and have fixed width and height, so that there will be no problems such as misalignment due to different sizes when the images are rotated. Use absolute positioning in container elements so that individual image elements appear in the same position.
- Picture switching
The function of automatic and manual switching of pictures is realized through JavaScript code. For automatic switching, you need to consider using a timer, while manual switching can be achieved using mouse hover and mouse click events.
- Focus indicator
Design a focus indicator bar suspended at the bottom so that the focus of the current picture can be clearly expressed. The focus indicator bar usually consists of a number of small dots, and the dots corresponding to the current image are distinguished (for example, by changing color). When implemented at the JavaScript code level, the small dots corresponding to the image can be changed accordingly based on the number or index of each image.
- Transition effect
In order to make the image carousel effect more smooth and natural, you need to use transition effect. Transition effects can show corresponding display effects when transitioning from one picture to the next, such as fade in and fade out, rotation and zoom, etc. The transition effect of CSS3 can be used during the implementation process, or JavaScript can be used to achieve the transition effect.
3. Carousel implementation code example
The following provides a JavaScript code example to demonstrate how to use JavaScript to achieve a carousel effect one by one. Through this example, you can see that image carousel is not difficult and only requires some basic knowledge of HTML, CSS and JavaScript to implement.
The HTML code is as follows:
<div id="img_container"> ??<img src="image1.jpg" alt="image1"> ??<img src="image2.jpg" alt="image2"> ??<img src="image3.jpg" alt="image3"> </div> <div id="indicators"></div>
The div#img_container
is the image container, and each img
tag is nested in the container in turn;div#indicators
is an indicator container that contains multiple indicator elements.
CSS code is as follows:
#img_container{ ??position:relative; ??overflow:hidden; ??height:400px; ??width:600px; } #img_container?img{ ??position:absolute; ??width:600px; ??height:400px; ??z-index:1; ??opacity:0; ??transition:opacity?1s?ease-in-out; } #img_container?img.active{ ??opacity:1; ??z-index:2; } #indicators{ ??position:absolute; ??width:100%; ??bottom:20px; ??text-align:center; } .indicator{ ??display:inline-block; ??height:10px; ??width:10px; ??border-radius:50%; ??margin:0?10px; } .indicator.active{ ??background-color:red; }
#img_container
uses the position:relative
attribute in CSS to define the elements inside the image container Use relative position for layout; opacity
attribute sets transparency, transition
attribute is transition attribute; #indicators
is positioned at the bottom and centered using centered text alignment. .indicator
is the indicator style.
The JavaScript code is as follows:
const?container?=?document.getElementById('img_container'); const?images?=?container.querySelectorAll('img'); const?indicators?=?document.getElementById('indicators'); const?dots?=?[]; let?currentImgIndex?=?0; let?interval; images[currentImgIndex].classList.add('active'); for(let?i?=?0;?i?< images.length; i++){ const dot = document.createElement('span'); dot.className = "indicator"; dot.addEventListener('click', () =>?{ ????clearInterval(interval); ????currentImgIndex?=?i; ????updateImages(); ????autoNext(); ??}); ??indicators.appendChild(dot); ??dots.push(dot); } function?updateImages(){ ??images.forEach(image?=>?image.classList.remove('active')); ??dots.forEach(dot?=>?dot.classList.remove('active')); ??images[currentImgIndex].classList.add('active'); ??dots[currentImgIndex].classList.add('active'); } function?autoNext(){ ??clearInterval(interval); ??interval?=?setInterval(()?=>?{ ????currentImgIndex++; ????if(currentImgIndex?>=?images.length){ ??????currentImgIndex?=?0; ????} ????updateImages(); ??},?3000); } autoNext();
In the JavaScript code, first obtain the container element and the internal image element, and set the index value of the current image (currentImgIndex
) and TimersetInterval
to control the effect of image carousel. At the same time, use updateImages()
to update the activation status of the current image and focus indicator, and use autoNext()
to achieve the automatic carousel effect.
4. Summary
This article introduces the basic principles and implementation technical details of using JavaScript to implement advertising image rotation, including image switching, focus indication, transition effects, etc. The code examples introduced can also be used as a reference in actual applications to better implement the web page ad rotation function. Of course, as JavaScript technology continues to be updated, this implementation may also change.
The above is the detailed content of How to achieve advertising image carousel effect with JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

ToimplementdarkmodeinCSSeffectively,useCSSvariablesforthemecolors,detectsystempreferenceswithprefers-color-scheme,addamanualtogglebutton,andhandleimagesandbackgroundsthoughtfully.1.DefineCSSvariablesforlightanddarkthemestomanagecolorsefficiently.2.Us

The topic differencebetweenem, Rem, PX, andViewportunits (VH, VW) LiesintheirreFerencepoint: PXISFixedandbasedonpixelvalues, emissrelative EtothefontsizeFheelementoritsparent, Remisrelelatotherootfontsize, AndVH/VwarebaseDontheviewporttimensions.1.PXoffersprecis

CSSHoudini is a set of APIs that allow developers to directly manipulate and extend the browser's style processing flow through JavaScript. 1. PaintWorklet controls element drawing; 2. LayoutWorklet custom layout logic; 3. AnimationWorklet implements high-performance animation; 4. Parser&TypedOM efficiently operates CSS properties; 5. Properties&ValuesAPI registers custom properties; 6. FontMetricsAPI obtains font information. It allows developers to expand CSS in unprecedented ways, achieve effects such as wave backgrounds, and have good performance and flexibility

CSSgradientsenhancebackgroundswithdepthandvisualappeal.1.Startwithlineargradientsforsmoothcolortransitionsalongaline,specifyingdirectionandcolorstops.2.Useradialgradientsforcirculareffects,adjustingshapeandcenterposition.3.Layermultiplegradientstocre

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

Choosing the correct display value in CSS is crucial because it controls the behavior of elements in the layout. 1.inline: Make elements flow like text, without occupying a single line, and cannot directly set width and height, suitable for elements in text, such as; 2.block: Make elements exclusively occupy one line and occupy all width, can set width and height and inner and outer margins, suitable for structured elements, such as; 3.inline-block: has both block characteristics and inline layout, can set size but still display in the same line, suitable for horizontal layouts that require consistent spacing; 4.flex: Modern layout mode, suitable for containers, easy to achieve alignment and distribution through justify-content, align-items and other attributes, yes

InternationalizationandlocalizationinVueappsareprimarilyhandledusingtheVueI18nplugin.1.Installvue-i18nvianpmoryarn.2.CreatelocaleJSONfiles(e.g.,en.json,es.json)fortranslationmessages.3.Setupthei18ninstanceinmain.jswithlocaleconfigurationandmessagefil

In Vue, provide and inject are features for directly passing data across hierarchical components. The parent component provides data or methods through provide, and descendant components directly inject and use these data or methods through inject, without passing props layer by layer; 2. It is suitable for avoiding "propdrilling", such as passing global or shared data such as topics, user status, API services, etc.; 3. Note when using: non-responsive original values ??must be wrapped into responsive objects to achieve responsive updates, and should not be abused to avoid affecting maintainability.
