简体   繁体   English

Javascript React 图像玻璃放大镜

[英]Javascript React Image Glass Magnifier

I have this glass magnifier (from https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_image_magnifier_glass ), which is opening fine onClick in my react project, but I want to make it to toggle open/close on further clicks but it is not closing.我有这个玻璃放大镜(来自https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_image_magnifier_glass ),它在我的 react/close 项目中打开了很好的 onClick,但我想让它打开进一步的点击,但它没有关闭。

This is my function which is supposed to achieve that, but somehow the zoom remains always open, no matter if my zoomActive state is set at true or false.这是我的 function 应该可以实现这一点,但是无论我的 zoomActive state 设置为 true 还是 false,缩放始终保持打开状态。 Can anyone tell me what am I doing wrong?谁能告诉我我做错了什么? Thanks!谢谢!

 const [zoomActive, setZoomActive] = useState(false)

    /* Initiate Magnify Function
with the id of the image, and the strength of the magnifier glass:*/
    const handleMagnifier = () => {
        setZoomActive(!zoomActive)
        zoomActive && magnify(myImageId, 3)
        console.log('MAGNIFIER-GLASS-STATE???', zoomActive)
    }

Here the onClick function:这里是 onClick function:

 <div
                                    className="img-magnifier-container"
                                    onClick={handleMagnifier}
                                >
                                    <img
                                        id={myImageId}
                      
                                        src={graphicImage}
                                        alt="mobile graphic"
                                    />
                                </div>

And the CSS: CSS:

.img-magnifier-container {
    position: relative;
    cursor: zoom-in;
}
.img-magnifier-glass {
    position: absolute;
    border: 3px solid $tangerine;
    border-radius: 50%;
    cursor: none;
    /*Set the size of the magnifier glass:*/
    width: 200px;
    height: 200px;
}

Just in case it helps anyone, removing the class did the trick for me.以防万一它对任何人都有帮助,删除 class 对我有用。 Like this:像这样:

 const handleMagnifier = () => {
        setZoomActive(!zoomActive)
        let glass = document.getElementsByClassName('img-magnifier-glass')
        !zoomActive ? magnify(myImageId, 3) : glass[0].removeAttribute('class')
    }

Not sure if it is the best approach, but it works.不确定这是否是最好的方法,但它有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM