我正在开发一个具有花哨视差滚动背景的网站,并遵循了Mohiuddin Parekh的教程(可在此处获得)
这是我的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
});
}
});