简体   繁体   English

javascript的窗口宽度条件

[英]condition of window width for javascript

New to js and trying to apply some lines of code only when the window is larger than 768 pixels. js的新增功能,仅在窗口大于768像素时才尝试应用一些代码行。

I've come up with this: 我想出了这个:

if ($(window).width() > 768) {
    const central = document.querySelector('.central');

    const tl = new TimelineMax();

    tl.fromTo(central,1,{height:'0vh'},{height:'80vh'})
    .fromTo(central,1,{width:'100vw'},{width:'80vw'});
 }

Loading in the HTML file this two lines: 在HTML文件中加载以下两行:

<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TimelineMax.min.js" 
integrity="sha256-fIkQKQryItPqpaWZbtwG25Jp2p5ujqo/NwJrfqAB+Qk=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/2.1.3/TweenMax.min.js" 
integrity="sha256-lPE3wjN2a7ABWHbGz7+MKBJaykyzqCbU96BJWjio86U=" crossorigin="anonymous"></script>
<script src='js.js'></script>

Without the if condition it runs fine, so the condition is wrongly applied, can you help me to fix it? 如果没有if条件,该条件运行良好,那么该条件被错误地应用了,您能帮我解决这个问题吗?

Combine it with a resize event 将其与调整大小事件结合

$(window).resize(function() {
 if ($(window).width() > 768) {
    const central = document.querySelector('.central');

    const tl = new TimelineMax();

    tl.fromTo(central,1,{height:'0vh'},{height:'80vh'})
    .fromTo(central,1,{width:'100vw'},{width:'80vw'});
 }
}).resize();

Added .resize() which will call the window.resize event on load. 添加了.resize() ,它将在加载时调用window.resize事件。

You have to listen to the window resize method. 您必须听听窗口调整大小方法。 Using vanilla Js you can wrap the main function like so: ` 使用香草Js,您可以像这样包装主要功能:

function responsiveFeature(){
  if (window.innerWidth < 768) {
    const central = document.querySelector('.central');
    const tl = new TimelineMax();
    tl.fromTo(central,1,{height:'0vh'},{height:'80vh'})
    .fromTo(central,1,{width:'100vw'},{width:'80vw'});
  }
}
`

then run the code on page loaded : ` 然后在加载的页面上运行代码:

document.addEventListener('DOMContentLoaded', (event) => {
    responsiveFeature();
});

and trigger the resize event :

window.addEventListener('resize',(event) => {
    responsiveFeature();
});

` `

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

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