【问题标题】:Different Zoom effect on Desktop and Mobile桌面和移动设备上不同的缩放效果
【发布时间】:2021-12-13 00:27:28
【问题描述】:

我正在使用这个 JS 和 CSS 为标题图像添加缩放效果。它在桌面上完美运行。

问题在于移动英雄图像没有“填充”整个容器。

所以我需要有 2 个不同的 JS 和 2 个不同的 % 设置,以使其在桌面和移动设备上都可以工作。

是否有一种解决方案可以根据屏幕尺寸制作一个满足我的 2 个不同需求的脚本? “此功能适用于桌面,此功能适用于移动设备”?

对于那些知道我正在使用 GeneratePress 的 Elements 功能来显示整个网站的英雄标题的人。

这是适用于桌面的 JS + CSS:

JS

<script>
var pagehero = document.querySelector('.page-hero');

function hero_animation(){
        pagehero.style.backgroundSize = 100+'%';
        pagehero.style.opacity = '1';
}
    
    document.onload = hero_animation();
</script>

CSS

.page-hero {
     transition: background-size 1s cubic-bezier(0.1, 0.135, 0.15, 0.86), opacity 1s ease-out 0.1s !important;
    opacity: 0; background-size: 150% auto;
}

这是我需要为移动设备添加的 JS + CSS:

JS

<script>
var pagehero = document.querySelector('.page-hero');

function hero_animation(){
        pagehero.style.backgroundSize = 200+'%';
        pagehero.style.opacity = '1';
}
    
    document.onload = hero_animation();
</script>

CSS

.page-hero {
     transition: background-size 1s cubic-bezier(0.1, 0.135, 0.15, 0.86), opacity 1s ease-out 0.1s !important;
    opacity: 0; background-size: 300% auto;
}

感谢您的帮助!

【问题讨论】:

    标签: javascript css zooming css-transitions background-size


    【解决方案1】:

    当文档 html/body 被加载时,您正在调用该函数。

    <script>
    var pagehero = document.querySelector('.page-hero');
    
    function hero_animation(){
            pagehero.style.backgroundSize = 100+'%';
            pagehero.style.opacity = '1';
    }
        
        document.onload = hero_animation();
    </script>
    

    改成这样:

    <script>
    var pagehero = document.querySelector('.page-hero');
    
    function hero_animation(){
            pagehero.style.backgroundSize = 100+'%';
            pagehero.style.opacity = '1';
    }
        
        document.onload = hero_animation;
    </script>
    

    或者这个:

    <script>
    var pagehero = document.querySelector('.page-hero');
    
    function hero_animation(){
            pagehero.style.backgroundSize = 100+'%';
            pagehero.style.opacity = '1';
    }
        
        document.onload = function() { hero_animation() };
    </script>
    

    其次,您应该将100/200 更改为字符串。 JavaScript 区分大小写:

    pagehero.style.backgroundSize = '100' + '%';
    

    或者

    pagehero.style.backgroundSize = (Number(100).toString()) + '%';
    

    【讨论】:

    • 感谢您的评论,但您对“document.onload”部分的建议不起作用,两者都破坏了英雄形象。顺便说一句,我正在查看的行为是在页面加载时对英雄图像产生缩放效果,而我正在使用的实际功能在桌面上完美运行。我的问题是在移动设备上使用不同的功能。如果您对我的移动与桌面问题有任何建议,我会很高兴。
    • 好的,我认为您正在寻找的是“响应式网页设计”。看看这个:w3schools.com/whatis/whatis_responsive.asp;问题是您在 CSS 中设置的绝对尺寸仅与您设备的视口相匹配。您需要在样式中使用相对单位/大小,以便它与浏览器的调整大小相匹配。如果您想要缩放效果,请查看:w3schools.com/howto/howto_css_zoom_hover.asp
    • 不,这不是我要找的。不过还是谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-11
    • 2013-03-11
    • 2016-09-26
    • 2018-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多