简体   繁体   English

设置顶部和左侧百分比而不是像素

[英]Setting top and left in percent instead of pixels

I am using codrops image reveal hover effect on a project https://tympanus.net/codrops/2018/11/27/image-reveal-hover-effects/ and it is working fine (i am using effect 5).我在项目https://tympanus.net/codrops/2018/11/27/image-reveal-hover-effects/上使用 codrops 图像显示悬停效果,它工作正常(我正在使用效果 5)。

I want to make a smalle change to this bit我想对这一点做一个小小的改变

            this.positionElement = (ev) => {
            const mousePos = getMousePos(ev);
            const docScrolls = {
                left : document.body.scrollLeft + document.documentElement.scrollLeft,
                top : document.body.scrollTop + document.documentElement.scrollTop
            };
            this.DOM.reveal.style.top = `${mousePos.y+20-docScrolls.top}px`;
            this.DOM.reveal.style.left = `${mousePos.x+20-docScrolls.left}px`;
        };

The bit where it sets the elements position, the last part, is set in px, is i possible to set that part in percent instead?, I want the image to be centred under the mouse cursor.它设置元素位置的位,最后一部分,以 px 为单位设置,我可以用百分比设置该部分吗?,我希望图像在鼠标光标下居中。 I can do it by setting the value to minus half the image width and height, but thats not good if i want to make the image smaller on smaller screens.我可以通过将值设置为图像宽度和高度的减半来实现,但是如果我想让图像在较小的屏幕上变小,那就不好了。 So a -50% value would be better.所以 -50% 的值会更好。

you should change just the css of the class hover-reveal so it would include the line:您应该只更改hover-reveal类的 css,以便它包含以下行:

transform: translate(-50%, -50%);

that way the image would be centered right under the mouse when it hovers the text because you moved it 50% of the height and length of the picture up and right.这样,当它悬停文本时,图像将在鼠标正下方居中,因为您将其向上和向右移动了图片高度和长度的 50%。

seems to me that what you need to change is not the pixel to a percentage but the anchor of the picture you want to reveal.在我看来,您需要更改的不是pixel到百分比,而是要显示的图片的锚点。 which you can change via:您可以通过以下方式更改:

transform: translate( 0, -50%); 

I'm not sure the first input changes the x axis and second argument y or vise versa.我不确定第一个输入会更改x轴和第二个参数y ,反之亦然。 but it's one way or another.但这是一种或另一种方式。

hope I've been some help!希望我有所帮助!

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

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