[英]Prevent script from executing based on screen size
I am currently trying to prevent the following Javascript from executing for screens that are smaller than 769px. 我目前正在尝试阻止以下Javascript对小于769px的屏幕执行。 I am a total Javascript newbie, this script is from a Codrops tutorial on how to animate a header on scroll. 我是Java的新手,该脚本来自Codrops教程,内容涉及如何在滚动上设置标题动画。 I have made a small modification that allows me to use images. 我做了一个小的修改,使我可以使用图像。 The original script was for text elements only. 原始脚本仅用于文本元素。 Here is the slightly modified script in its entirety. 这是整体上稍有修改的脚本。
var cbpAnimatedHeader = (function() {
var docElem = document.documentElement,
header = document.querySelector( '.header-outer' ),
logo = document.querySelector( '.logo' )
didScroll = false,
changeHeaderOn = 300;
function init() {
window.addEventListener( 'scroll', function( event ) {
if( !didScroll ) {
didScroll = true;
setTimeout( scrollPage, 250 );
}
}, false );
}
function scrollPage() {
var sy = scrollY();
if ( sy >= changeHeaderOn ) {
classie.add( header, 'header-shrink' );
classie.add( logo, 'logo-shrink' );
}
else {
classie.remove( header, 'header-shrink' );
classie.remove( logo, 'logo-shrink' );
}
didScroll = false;
}
function scrollY() {
return window.pageYOffset || docElem.scrollTop;
}
init();
})();
I did see someone else on StackOverflow ask a similar question, but the solution ( if ($(window).width() > 768) {
) that was given to him hasn't worked for me so far, I am sure that I am applying it incorrectly. 我确实看到StackOverflow上的其他人也提出了类似的问题,但是到目前为止,提供给他的解决方案( if ($(window).width() > 768) {
)不适用于我,我敢肯定应用不正确。
Any help would be greatly appreciated :) 任何帮助将不胜感激 :)
The reason 原因
$(window).width()
isn't working for you is because it uses jQuery , which you're not using it seems. 对您不起作用是因为它使用的是jQuery ,而您似乎没有使用它。
Instead use: 而是使用:
window.innerWidth
So, do this: 因此,请执行以下操作:
if ( sy >= changeHeaderOn && window.innerWidth > 768 ) {
classie.add( header, 'header-shrink' );
classie.add( logo, 'logo-shrink' );
}
Try this js, 试试这个js,
window.outerWidth,
You can check for all window associated objects via console.log(window). 您可以通过console.log(window)检查所有与窗口相关的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.