国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Web Front-end Front-end Q&A How to achieve advertising image carousel effect with JavaScript

How to achieve advertising image carousel effect with JavaScript

Apr 19, 2023 pm 02:14 PM

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.

  1. 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.

  1. 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.

  1. 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.

  1. 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(&#39;span&#39;);
  dot.className = "indicator";
  dot.addEventListener(&#39;click&#39;, () =>?{
????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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How can CSS be used to implement dark mode theming on a website? How can CSS be used to implement dark mode theming on a website? Jun 19, 2025 am 12:51 AM

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

Can you explain the difference between em, rem, px, and viewport units (vh, vw)? Can you explain the difference between em, rem, px, and viewport units (vh, vw)? Jun 19, 2025 am 12:51 AM

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

What are CSS Houdini APIs, and how do they allow developers to extend CSS itself? What are CSS Houdini APIs, and how do they allow developers to extend CSS itself? Jun 19, 2025 am 12:52 AM

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

How can CSS gradients (linear-gradient, radial-gradient) be used to create rich backgrounds? How can CSS gradients (linear-gradient, radial-gradient) be used to create rich backgrounds? Jun 21, 2025 am 01:05 AM

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

What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? What is the significance of Vue's reactivity transform (experimental, then removed) and its goals? Jun 20, 2025 am 01:01 AM

ReactivitytransforminVue3aimedtosimplifyhandlingreactivedatabyautomaticallytrackingandmanagingreactivitywithoutrequiringmanualref()or.valueusage.Itsoughttoreduceboilerplateandimprovecodereadabilitybytreatingvariableslikeletandconstasautomaticallyreac

What are the key differences between inline, block, inline-block, and flex display values? What are the key differences between inline, block, inline-block, and flex display values? Jun 20, 2025 am 01:01 AM

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

How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? How can internationalization (i18n) and localization (l10n) be implemented in a Vue application? Jun 20, 2025 am 01:00 AM

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

How does provide and inject allow for deep component communication without prop drilling in Vue? How does provide and inject allow for deep component communication without prop drilling in Vue? Jun 20, 2025 am 01:03 AM

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.

See all articles