Home Web Front-end JS Tutorial How to use JavaScript to slide the image left and right and add a zoom effect?

How to use JavaScript to slide the image left and right and add a zoom effect?

Oct 18, 2023 am 11:15 AM
javascript slide Zoom

JavaScript 如何实现图片的左右滑动并加入缩放效果?

JavaScript How to slide the image left and right and add a zoom effect?

With the development of the Internet, pictures have become an indispensable part of our daily lives. In web design, the way pictures are presented is also very important. This article will introduce how to use JavaScript to slide the image left and right and add a zoom effect.

1. HTML structure

First, we need to create an image container in HTML and nest the image element within it. For example:

<div class="slider">
  <img src="image1.jpg" alt="">
</div>
Copy after login

2. Add CSS styles

Next, we need to add some basic CSS styles to the image container to ensure that the image container can be displayed normally and have a certain size. For example:

.slider {
  width: 500px;
  height: 300px;
  overflow: hidden;
  position: relative;
}

.slider img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
Copy after login

3. To achieve the left and right sliding effect

First, we need to obtain the image container and image elements, and calculate the distance for each sliding. The code is as follows:

var slider = document.querySelector('.slider');
var image = document.querySelector('.slider img');
var slideDistance = 200; // 每次滑动的距离
Copy after login

Then, we can bind a sliding event to the image container and adjust the position of the image display according to the direction of sliding. The code is as follows:

slider.addEventListener('mousedown', startSlide);

function startSlide(e) {
  var startX = e.clientX;
  slider.addEventListener('mousemove', slideImage);

  function slideImage(e) {
    var moveX = e.clientX - startX;
    image.style.transform = 'translateX(' + moveX + 'px)';
  }

  slider.addEventListener('mouseup', stopSlide);
  slider.addEventListener('mouseleave', stopSlide);

  function stopSlide(e) {
    slider.removeEventListener('mousemove', slideImage);
    var moveX = e.clientX - startX;
    var absMoveX = Math.abs(moveX);
    var direction = moveX > 0 ? 'right' : 'left';

    if (absMoveX > slideDistance) {
      if (direction === 'right') {
        slideTo('prev');
      } else {
        slideTo('next');
      }
    } else {
      resetSlide();
    }
  }

  function resetSlide() {
    image.style.transform = 'translateX(0)';
  }

  function slideTo(direction) {
    var currentImageIndex = getIndex(image.getAttribute('src'));

    if (direction === 'prev') {
      currentImageIndex--;
    } else {
      currentImageIndex++;
    }

    if (currentImageIndex < 0) {
      currentImageIndex = imageList.length - 1;
    } else if (currentImageIndex >= imageList.length) {
      currentImageIndex = 0;
    }

    image.src = imageList[currentImageIndex];
    resetSlide();
  }
}
Copy after login

4. Add zoom effect

If we want to achieve the zoom effect while sliding the picture, we can get the sliding distance in the sliding event and adjust it according to the distance to resize the image. The code is as follows:

// 在 slideImage 函数中添加以下代码

function slideImage(e) {
  var moveX = e.clientX - startX;
  var scale = 1 - Math.abs(moveX) / (slider.offsetWidth / 2);

  if (scale < 0.3) {
    scale = 0.3;
  }

  image.style.transform = 'translateX(' + moveX + 'px) scale(' + scale + ')';
}
Copy after login

Through the implementation of the above code, we can slide the image left and right on the web page and add a zoom effect. At the same time, during the implementation process, we can adjust the sliding distance, scaling ratio, etc. as needed to meet specific design needs.

The above is the detailed content of How to use JavaScript to slide the image left and right and add a zoom effect?. 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

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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 to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Safari zoom issue on iPhone: Here's the fix Safari zoom issue on iPhone: Here's the fix Apr 20, 2024 am 08:08 AM

If you don't have control over the zoom level in Safari, getting things done can be tricky. So if Safari looks zoomed out, that might be a problem for you. Here are a few ways you can fix this minor zoom issue in Safari. 1. Cursor magnification: Select "Display" > "Cursor magnification" in the Safari menu bar. This will make the cursor more visible on the screen, making it easier to control. 2. Move the mouse: This may sound simple, but sometimes just moving the mouse to another location on the screen may automatically return it to normal size. 3. Use Keyboard Shortcuts Fix 1 – Reset Zoom Level You can control the zoom level directly from the Safari browser. Step 1 – When you are in Safari

How to zoom pages side by side in word How to zoom pages side by side in word Mar 19, 2024 pm 07:19 PM

When we use word documents to edit files, sometimes there are many pages. We want to display them side by side and check the overall effect. However, because we don’t know how to operate, we often need to scroll for a long time to view page by page. I don’t know if you have ever encountered a similar situation. In fact, we can easily solve it at this time as long as we learn how to set the word zoom pages side by side. Below, let’s take a look and learn together. First, we create and open a new page in the Word document, and then enter some simple content to make it easier to distinguish. 2. For example, if we want to realize word zoom and side-by-side display, we need to find [View] in the menu bar, and then select [Multiple Pages] in the view tool options, as shown in the figure below: 3. Find [Multiple Pages] and click,

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Word document editing tips: Make two pages of content into one Word document editing tips: Make two pages of content into one Mar 25, 2024 pm 06:06 PM

In Microsoft Word documents, you often encounter the situation of merging two pages of content into one page, especially when you need to save paper or when you need to print a double-sided document. Several common methods to achieve this goal will be introduced below. Method 1: Adjust the page margins. First open the Word document and find the &quot;Page Layout&quot; option in the menu bar. After clicking, the page layout settings menu will pop up. Here you can adjust the page margins, including the top, bottom, left, and right margins. Generally speaking, making the top and bottom margins smaller will allow the content to fit within one page. you can taste

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

What should I do if my mobile phone screen is hard to slide and dry? What should I do if my mobile phone screen is hard to slide and dry? Dec 04, 2023 pm 03:51 PM

Solutions for mobile phone screens that are difficult to slide and dry: 1. Humidify the screen; 2. Clean the screen regularly; 3. Increase the sliding strength of your fingers; 4. Use mobile phone screen protectors; 5. Replace protective covers; 6. Keep hands moist; 7. , handle it cleanly when applying the film; 8. Use lubricant; 9. Use gloves; 10. Adjust the screen brightness; 11. Replace the mobile phone. Detailed introduction: 1. Humidify the screen, place a humidifier next to the screen or spray some water to increase the humidity in the air, thereby reducing the dryness of the screen; 2. Clean the screen regularly, use professional screen cleaner, etc.

See all articles