SoFunction
Updated on 2025-03-01

Use native JavaScript to achieve magnifying glass effects

Requirements List

Mouse enters the box to control the mask layer and enlarges the box to display and hide

The mask layer moves with the mouse and the mask layer does not exceed the box's limit range

Picture box/mask layer/magnification box These three can be adapted in width, height and size

HTML

<div class="outer"
    <!-- Picture box box1 -->
    <div class="box">
        <img src="./" alt="">
        <!-- Mask layer -->
        <div class="mask"></div>
    </div>
    <!-- Zoom in the box -->
    <div class="box2"></div>
</div>

CSS

.outer {
    display: flex;
}
.box {
    /* Can change the width and height here */
    width: 400px;
    height: 400px;
    background: green;
    position: relative;
    margin-left: 100px;
}
.box img {
    width: 100%;
    height: 100%;
}
.box2 {
    /* Can change the width and height here */
    width: 600px;
    height: 600px;
    background-image: url(./);
    background-repeat: no-repeat;
    background-size: 400% 400%;
    display: none;
    margin-left: 20px;
}
.mask {
    /* Can change the width and height here */
    width: 200px;
    height: 200px;
    background: rgba(0, 0, 0, .5);
    display: none;
    position: absolute;
}

Javascript

        // Get the elements of three boxes        const mask = ('.mask')
        const box1 = ('.box')
        const box2 = ('.box2')

        // Function: Display and hide the mask layer and enlarge box        ('mouseenter', () => {
             = 'block'
             = 'block'
        })
        ('mouseleave', () => {
             = 'none'
             = 'none'
        })

        // Move the mouse into the box        ('mousemove', (e) => {
            // Get the mouse in the x-axis position of the current viewable window            // ().left Get the position on the left of the current box (range: viewable window)            // Location from top
            // The reason for subtracting a distance from the top is that the getBoundingClientRect method is relative to the viewable window.            // If our current element appears in the scrollbar, subtract one of its scrollbar height so that it will not be misaligned.            let x =  - ().left - 
            let y =  - ().top -   // Subtract the distance from the top of the box position
            // Specify that the mask layer moves in the current parent box            if (x >= 0 && x <=  && y >= 0 && y <= ) {

                // Initialize the movable positions of x and y                let mx = 0
                let my = 0

                // ------------------------------------------------------------------------------------------------------------------------------                let maskWidth = 
                let maskWidthHalf =  / 2
                let currentBoxWidth = 

                let maskHeight = 
                let maskHeightHalf =  / 2
                let currentBoxHeight = 

                // Process the x part                // It cannot be moved within [mask itself half]                if (x < maskWidthHalf) mx = 0
                // Only if you can move it in the [box - half of the mask] section                if (x >= maskWidthHalf && x <= currentBoxWidth - maskWidthHalf) mx = x - maskWidthHalf
                // Arrive [Box - Mask Half] and can't move any more                if (x > currentBoxWidth - maskWidthHalf) mx = currentBoxWidth - maskWidth

                // Handle the y part (same)                if (y < maskHeightHalf) my = 0
                if (y >= maskHeightHalf && y <= currentBoxHeight - maskHeightHalf) my = y - maskHeightHalf
                if (y > currentBoxHeight - maskHeightHalf) my = currentBoxHeight - maskHeight

                // Let the mask layer move                 = mx + 'px'
                 = my + 'px'

                // --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------                // 1. Multiple of background magnification == Width of box 1 / Width of cover layer                let scaleWidth = ( / ) * 100
                let scaleHeight = ( / ) * 100
                 =
                    `${scaleWidth + '%'} ${scaleHeight + '%'}`
                    
                (scaleWidth, 'Magnification');

                // 2. Number of steps to walk = enlarge box width / cover layer width                let stepWidth = ( / )
                let stepHeight = ( / )
                
                // Add a negative sign here because it needs to move from the opposite direction, while the positive number moves to the right                 = -stepWidth * mx + 'px'
                 = -stepHeight * my + 'px'
                
                (mx, 'box1Total movable distance = box1Width - 遮罩层Width');
                (stepWidth, 'Walking multiples(Step count) = box2Width / maskWidth ');
                (-stepWidth * mx, 'Total movable distance * Number of walking steps; indicates the distance used by the mask layer to end from one side to the other');
            }
        })

analyze

1. How many times the background is magnified depends on youThe current box itself widthandWidth of mask layer

Assume that it is currently a 400-width box and the mask layer has a width of 200

Then the picture in the enlarged box is 400 / 200 = 2 times, and the current ratio is 1:2

If it is currently a 600-width box, and the mask layer has a width of 100

Then the picture in the enlarged box is 600 / 100 = 6 times, and the current ratio is 1:6

2. The number of steps you walk depends on youEnlarge the box widthandCover layer width

Assuming that the current enlarged box width is 600 and the mask layer is 100, this means that it takes 6 times to walk from beginning to end. If box1 is 200 wide, then the mx movable distance is 100, which means100 * 6 = 600Only after walking 600 distances can the background image magnified by 6 times be fully displayed.

3. The above theory exists:

You can achieve box1/box2/mask layer. These three boxes can be changed arbitrarily, so as not to affect scaling.

This is the end of this article about using native JavaScript to achieve magnifying glass effects. For more related JavaScript magnifying glass content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!