javascript - 在移动设备上禁用视差

标签 javascript jquery css mobile parallax

我正在开发一个具有精美视差滚动背景的网站,并遵循 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/

相关文章:

css - 3 列流体分区显示故障 : "Hanging" Individual Divs

css - Angular-cli----> CRUD操作更新员工数据不显示姓名字段显示其他字段

javascript - 为什么 jquery 选项选择不起作用

jquery - 使用 Backbone 在多个异步 ajax 调用后渲染 View

javascript - $.ajax 调用失败,数据类型为 json

c# - 如何在网络技术上制作特定日期和时间的倒计时器

php - PHP 和 Javascript 之间的通信

javascript - 在 DC 中为 D3 绘制多维

javascript - 如何使用 jQuery 匹配两行内两个 anchor 的索引?

javascript - 在选中的单选按钮和复选框按钮上触发动画