我正在开发一个具有精美视差滚动背景的网站,并遵循 Mohiuddin Parekh 的教程(可用 here )
这是我的 JavaScript:
$(document).ready(function(){
// Cache the Window object
$window = $(window);
$('section[data-type="background"]').each(function(){
var $bgobj = $(this); // assigning the object
$(window).scroll(function() {
// Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -( ($window.scrollTop() - $bgobj.offset().top) / $bgobj.data('speed'));
// Put together our final background position
var coords = '50% '+ yPos + 'px';
// Move the background
$bgobj.css({ backgroundPosition: coords });
}); // window scroll Ends
});
});
这很好用。现在我想做的是,如果使用移动设备(最大宽度:768px)查看网站,则不执行 JavaScript。不幸的是,我不太确定如何实现这一点,感谢任何帮助:)
最佳答案
页面启动时触发文档就绪,并且当有人操作窗口时触发窗口大小
$( window ).resize(function() {
$window = $(window);
if( $window .width() > 800){
$('section[data-type="background"]').each(function(){
var $bgobj = $(this); // assigning the object
$(window).scroll(function() {
// Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -( ($window.scrollTop() - $bgobj.offset().top) / $bgobj.data('speed'));
// Put together our final background position
var coords = '50% '+ yPos + 'px';
// Move the background
$bgobj.css({ backgroundPosition: coords });
}); // window scroll Ends
});
}
});
$(document).ready(function(){
$window = $(window);
if( $window.width() > 800){
// Cache the Window object
$('section[data-type="background"]').each(function(){
var $bgobj = $(this); // assigning the object
$(window).scroll(function() {
// Scroll the background at var speed
// the yPos is a negative value because we're scrolling it UP!
var yPos = -( ($window.scrollTop() - $bgobj.offset().top) / $bgobj.data('speed'));
// Put together our final background position
var coords = '50% '+ yPos + 'px';
// Move the background
$bgobj.css({ backgroundPosition: coords });
}); // window scroll Ends
});
}
});
关于javascript - 在移动设备上禁用视差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22785473/